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

Automatically build and deploy using Docker+Jenkins

This article introduces Docker+Jenkins automatic ...

Classes in TypeScript

Table of contents 1. Overview 2. Define a simple ...

Enabling and configuring MySQL slow query log

Introduction MySQL slow query log is an important...

How to publish static resources in nginx

step Place the prepared static resource files in ...

Comprehensive understanding of line-height and vertical-align

Previous words Line-height, font-size, and vertica...

Sample code for highlighting search keywords in WeChat mini program

1. Introduction When you encounter a requirement ...

Encapsulate the navigation bar component with Vue

Preface: Fully encapsulating a functional module ...

Vue realizes the card flip effect

This article example shares the specific code of ...

MySql Group By implements grouping of multiple fields

In daily development tasks, we often use MYSQL...

Reasons and methods for Waiting for table metadata lock in MySQL

When MySQL performs DDL operations such as alter ...

In-depth analysis of HTML table tags and related line break issues

What is a table? Table is an Html table, a carrie...

MySQL 8.0.18 Installation Configuration Optimization Tutorial

Mysql installation, configuration, and optimizati...