Discuss the application of mixin in Vue

Discuss the application of mixin in Vue

Mixins provide a very flexible way to distribute reusable functionality among Vue components. A mixin object can contain arbitrary component options. When a component uses a mixin, all of the mixin's options will be "mixed" into the component's own options.

That is, after the mixin is introduced into the component, the content inside the component, such as data, method and other attributes, will be merged with the corresponding content of the parent component. This means that after the introduction, all the property methods of the parent component have been expanded.

For example, calling the sayHi method in two different components requires repeated definition. If the method is complex, the code will be more redundant, but using mixins is relatively simple.

First, define a mixin object in the mixin.js file:

let mixin = {
  data () {
    return {
      userName: 'mixin'
    }
  },
  created () {
    this.sayHello()
  },
  methods: {
    sayHello() {
      console.log(`${this.userName}, welcome`)
    }
  }
}

export default mixin

Then define two components and introduce them in the components respectively:

<script>
    import mixin from '../mixin'

    export default {
      mixins: [mixin]
    }
</script>

Then the print results of both components are:

If the userName is defined in the two component data, the printed result will refer to the userName in each component.

If the same method is defined repeatedly in the methods of two components, the method in the mixin will be overwritten.

Define your own userName and sayHi methods for one of the components:

<script>
    import mixin from '../mixin'

    export default {
      mixins: [mixin],
      data() {
        return {
          userName: 'BComponent'
        }
      },
      created () {
          this.sayHello()
      },
      methods: {
        sayHello() {
          console.log(`Hi, ${this.userName}`)
        }
      }
    }
</script>

Then print the result:

This is a bit like registering a vue public method that can be used in multiple components. Another point is similar to registering methods in the prototype object, and you can define methods with the same function name to overwrite them.

Mixins can also be registered globally, but they are generally not used globally because they will pollute the Vue instance.

I usually use this in my projects. For example, if a universal selector is used in multiple components, the options are: yes, no, you can use mixin to add a unified dictionary item filter to realize the echo of options.

1. First, create a Dictionary.js file to save the meaning of the dictionary items and expose them:

export const COMMON_SELECT = [
    { code: 0, label: 'Yes'},
    { code: 1, label: 'No'}
];

Note: The Dictionary.js file created here can also be used to loop options when the page is rendered. The specific code is as follows:

import { COMMON_SELECT } from '../constants/Dictionary.js'

export default {
    data() {
        return {
            comSelectOptions: COMMON_SELECT
        }
    }
}

<select v-mode="selStatus">
    <el-option v-for="item in comSelectOptions" :key="item.code" :label="item.label" :value="item.code"></el-option>
</select>

2. Then create a filter.js file to save the custom filter function:

import { COMMON_SELECT } from '../constants/Dictionary.js'

export default {
  filters:
    comSelectFilter: (value) => {
      const target = COMMON_SELECT.filter(item => {
        return item.code === value
      })
      return target.length ? target[0].label : value
    }
  }
}

3. Finally, introduce the filter method once in main.js:

import filter from './mixin/filter'
Vue.mixin(filter)

Oh, now we can use it in any component.

<template>
    <div>
        ....
        {{ status | comSelectFilter }}
        ....
    </div>  
</template>

The above is the detailed discussion of the application of mixin in vue. For more information about the application of mixin in vue, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • How to use mixins in Vue
  • Vue detailed explanation of mixins usage
  • A Deep Dive into Vue.js Mixins
  • Vue mixins scroll bottoming method
  • How to use Vue Mixins
  • Detailed explanation of Vue mixin

<<:  How to handle the tcp_mark_head_lost error reported by the Linux system

>>:  Detailed explanation of the use of default in MySQL

Recommend

Common methods and problems of Docker cleaning

If you use docker for large-scale development but...

border-radius method to add rounded borders to elements

border-radius:10px; /* All corners are rounded wi...

Why Use DOCTYPE HTML

You know that without it, the browser will use qui...

Detailed explanation of MySQL deadlock and database and table sharding issues

Record the problem points of MySQL production. Bu...

Teach you how to monitor Tomcat's JVM memory through JConsoler

Table of contents 1. How to monitor Tomcat 2. Jav...

Use auto.js to realize the automatic daily check-in function

Use auto.js to automate daily check-in Due to the...

Causes and solutions for MySQL data loss

Table of contents Preface Problem Description Cau...

HTML form and the use of form internal tags

Copy code The code is as follows: <html> &l...

How to represent various MOUSE shapes

<a href="http://" style="cursor...

Detailed explanation of slots in Vue

The reuse of code in vue provides us with mixnis....

Tips for viewing History records and adding timestamps in Linux

Tips for viewing History records and adding times...

VMWare Linux MySQL 5.7.13 installation and configuration tutorial

This article shares with you the tutorial of inst...

A useful mobile scrolling plugin BetterScroll

Table of contents Make scrolling smoother BetterS...