How to use Vue3 mixin

How to use Vue3 mixin

Vue 2 uses optional APIs such as data, methods, watch, computed, and lifecycle hook functions.

mixin provides a very flexible way to distribute reusable functions in vue components. A mixin object can contain any component options. When a component uses a mixin object, all the options of mixin object will be mixed into the component's own options.

1. How to use mixin?

In layman's terms, mixin object extracts some common options of components, such as data in data , methods, calculated properties, and lifecycle hook functions, and then introduces them into the component, which can be merged with the options of the component itself.

Example 1:

<script>

const myMixin = {

 data(){

  return {

   num:520

  }

 },

 mounted(){

  console.log('mixin mounted');

 }

}

export default {

  mixins:[myMixin],

}

</script>

is equivalent to:

<script>

export default {

 data(){

  return {

   num:520

  }

 },

 mounted(){

  console.log('mixin mounted');

 }

}

</script>

The advantage of doing this is that you can extract the common options of multiple components into a mixin object, which can be directly introduced when needed.

2. Notes on using mixin

The options included in mixin can also be included in the component. What if some of the properties of the options included in mixin are the same? What to do if a method with the same name exists in both mixin and the component? Or when both contain lifecycle hook functions, which one is executed first and which one is executed later? Next, let's take a look at the points we should pay attention to when using mixin.

2.1. When using a mixin object, what should I do if the component and the mixin contain the same options?

Example 2 : Both the mixin object and the instance contain the data option, with two different variables inside

<template>

 <div>

  {{qdr}} - {{name}} 

 </div>

</template>

<script>

const myMixin = {

 data(){

  return {

   name:'A little sister who loves front-end'

  }

 }

}

export default {

 mixins:[myMixin],

 data(){

  return {

   qdr: "front-end person"

  }

 }

}

</script>

After running, we find that both variables can be used, and data in mixin object is merged with the data option in the instance. The same is true for methods and computed .

What happens if we change the two variables in the previous example to have the same name?

2.2. What should I do if the mixin object options used and the options in the instance have the same attributes?

Example 3 : The same variable name name exists in data

<template>

 <div>

  {{name}} 

 </div>

</template>

<script>

const myMixin = {

 data(){

  return {

   name:'A little sister who loves front-end'

  }

 }

}

export default {

 mixins:[myMixin],

 data(){

  return {

   name: "Front-end person"

  }

 }

}

</script>

Running result: the name value is "Front-end Person".

When the attribute values ​​are the same, the proximity principle will be chosen and the value in the instance will be inherited first, so the attributes of mixin object will be overwritten by the attributes in the instance.

2.3. Mixin objects can also add lifecycle hook functions

Which one will be executed first, mixin or instance?

Example 4 : Adding lifecycle hook functions mixin , taking mounted as an example

const myMixin = {

 mounted(){

  console.log('mixin mounted');

 }

}

export default {

 mixins:[myMixin],

 mounted(){

  console.log('mounted');

 }

}

Running results:

We found that lifecycle functions are executed together, with those in mixin being executed first, and then those in instance.

3. Mixin custom attributes

$options is used to initialize the options for the current component instance. It is useful when you need to include a custom property in the options.

In short, $options is used to call mixin custom properties in the instance.

Example 5 : Adding custom attributes

const myMixin = {

  custom:'custom attributes'

 }

Use in examples:



mounted(){

 console.log(this.$options.custom);

}

If the instance also contains a custom property with the same name, how will the priority be handled? What if we want to control the priority?

4. Merger Strategy

optionMergeStrategies option merge strategy, use optionMergeStrategies to define the merge rules when mixin custom attributes conflict with the attributes in the instance, that is, which one should be used first.

Rules of Use:

app.config.optionMergeStrategies.propertyName=(mixinVal,appVal)=>{

  return appVal || mixinVal // Determine which attribute value is returned first}

According to Example 5 above , add custom attributes to the instance and run it to view the results.

Example 6 : Validating mixin and instance attribute precedence

<script>

const myMixin = {

  custom:'mixin custom',

}

export default {

  custom:'app custom',

  mixins:[myMixin],

  mounted(){

    console.log(this.$options.custom); // Print result: app custom

  }

}

</script>

It is found that the attribute values ​​in mixin object are overwritten by the attribute values ​​in the instance. We can use the optionMergeStrategies attribute mentioned above to modify the merging rules of custom .

Import in main.js file:

app.config.optionMergeStrategies.custom=(mixinVal,appVal)=>{

 return mixinVal || appVal

}

After running again, we find that the printed result becomes the attribute value in the mixin:

console.log(this.$options.custom); // Print result: mixin custom

5. Global configuration mixin

If there are multiple components in the project that reuse certain options, we can use mixin object globally. An instance can also introduce multiple mixin objects.

The syntax is as follows:

app.mixin([ {}, {}, {} ])

This is the end of this article about how to use vue3 mixin. For more related vue3 mixin content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Example of communication between parent and child components of Vue (props, $ref, $emit)
  • How to use mixins in Vue
  • Detailed explanation of the use of Vue mixin
  • Detailed tutorial on using Mixin & extends in Vue
  • Detailed explanation of the failure of using ref responsiveness in defineProps in vue3
  • Vue component common method extraction mixin implementation
  • Notes on Vue parent-child components sharing mixins
  • Detailed explanation of Vue componentization (ref, props, mixin, plug-in)
  • ref, props, mixin attributes in Vue

<<:  HTML meta viewport attribute description

>>:  How to design high-quality web pages Experience in designing high-quality web pages (pictures and text)

Recommend

MySQL replication table details and example code

MySQL replication table detailed explanation If w...

Understanding of CSS selector weight (personal test)

Copy code The code is as follows: <style type=...

Solve the splicing problem of deleting conditions in myBatis

I just learned mybatis today and did some simple ...

How to pass W3C validation?

In addition to setting regulations for various ta...

Solution for using Baidu share on Https page

Since enabling https access for the entire site, ...

Explanation of the problem of selecting MySQL storage time type

The datetime type is usually used to store time i...

What you need to understand about MySQL locks

1. Introduction MySQL locks can be divided into g...

Problems with nodejs + koa + typescript integration and automatic restart

Table of contents Version Notes Create a project ...

Summary of the execution issues between mysql max and where

Execution problem between mysql max and where Exe...

Implementation of Vue single file component

I recently read about vue. I found a single-file ...

Example of MySQL slow query

Introduction By enabling the slow query log, MySQ...