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

js to achieve star flash effects

This article example shares the specific code of ...

Deep understanding of JavaScript syntax and code structure

Table of contents Overview Functionality and read...

Analysis of the reasons why MySQL field definitions should not use null

Why is NULL so often used? (1) Java's null Nu...

How to use selenium+testng to realize web automation in docker

Preface After a long time of reading various mate...

mysql 5.7.18 winx64 free installation configuration method

1. Download 2. Decompression 3. Add the path envi...

MySQL explain obtains query instruction information principle and example

explain is used to obtain query execution plan in...

mysql zip file installation tutorial

This article shares the specific method of instal...

JavaScript Basics Series: Functions and Methods

Table of contents 1. The difference between funct...

MySQL 8.0.20 Installation Tutorial with Pictures and Text (Windows 64-bit)

1: Download from mysql official website https://d...

How to recover accidentally deleted messages files in Linux

If there are files that are being used by a proce...

MySQL 8.0.11 compressed version installation tutorial

This article shares the installation tutorial of ...

Docker uses dockerfile to start node.js application

Writing a Dockerfile Taking the directory automat...

How to reference jQuery in a web page

It can be referenced through CDN (Content Delivery...

Docker Getting Started Installation Tutorial (Beginner Edition)

Doccer Introduction: Docker is a container-relate...

Detailed explanation of the TARGET attribute of the HTML hyperlink tag A

The hyperlink <a> tag represents a link poin...