Home  >  Article  >  Web Front-end  >  What are Mixins? Take you to understand Mixin mixing in Vue

What are Mixins? Take you to understand Mixin mixing in Vue

青灯夜游
青灯夜游forward
2022-03-21 11:42:1316000browse

What is Mixin? This article will take you through Mixin mixing in Vue, introduce the difference between Mixin and Vuex, and how to use Mixin. I hope it will be helpful to everyone!

What are Mixins? Take you to understand Mixin mixing in Vue

#The Vue framework now basically occupies half of the front-end, and Vue’s data-driven and component-based ideas are deeply rooted in the hearts of the people. Vue Family Bucket may be familiar to many friends, and it is also relatively easy to use at work. But I believe that there are still many friends who don’t know or haven’t used the Mixin in Vue that I’m talking about today. Or some friends saw a Mixin folder in it when they took over someone else’s Vue project, and they also use it, but they always use it. It's a state of confusion. Today we will talk about Mixin and try to avoid confusion in the future. [Related recommendations: vuejs video tutorial]

1. What is Mixin?

If we want to use a thing or tool, we must first understand what it is, so that we can prescribe the right medicine.

In fact, Mixin is not exclusive to Vue. It can be said to be an idea, or it means mixing in. Mixin (mixing in) is implemented in many development frameworks. What we mainly explain here is Vue. Mixin in.

Old rule, read the official documentation first.

Official explanation:

Mixin provides a very flexible way to distribute reusable functions in Vue components. A mixin can contain arbitrary component options. When a component uses a mixin, all of the mixin's options will be "mixed" into the options of the component itself.

Official explanations are usually obscure and difficult to understand, because they need to be professional and accurate!

We can use our own easy-to-understand words to say what Mixin is in Vue.

Folk explanation:

Extract the public logic or configuration of the component. When which component needs to be used, just mix the extracted part into the component. . This can not only reduce code redundancy, but also make later maintenance easier.

What needs to be noted here is: what is extracted is logic or configuration, not HTML code and CSS code. In fact, you can also change your mind. Mixins are components within components. Vue componentization makes our code more reusable. If there are duplicate parts between components, we use Mixin to separate them.

2. What is the difference between Mixin and Vuex?

The above point says that Mixin is a function that extracts public parts. In Vue, Vuex state management seems to do the same thing. It also extracts data that may be shared between components. The two seem to be the same, but in fact there are subtle differences. The differences are as follows:

  • Vuex public state management, if a certain data in Vuex is changed in one component, then all other components will reference Vuex The components in the data will also change accordingly.
  • The data and methods in Mixin are independent, and components do not affect each other after being used.

3. How to use?

We understand the concept of Mixin, so how to use it? This is our focus.

3.1 Preparation

Next, our mixin will be demonstrated in the Vue2.x scaffolding project.

Use Vue-cli to initialize the simplest project:

What are Mixins? Take you to understand Mixin mixing in Vue

##3.1 mixin definition

Definition of mixin also Very simple, it is just an object, but this object can contain some common configurations in Vue components, such as data, methods, created, etc.

Create a new mixin folder in the src directory of our project, and then create a new index.js file, which stores our mixin code.

The code is as follows:

// src/mixin/index.js
export const mixins = {
  data() {
    return {};
  },
  computed: {},
  created() {},
  mounted() {},
  methods: {},
};

What are Mixins? Take you to understand Mixin mixing in Vue

You can see that our mixin is very simple, mainly including a common Vue component logical structure.

Next let us simply write something in the mixin.

The code is as follows:

export const mixins = {
  data() {
    return {
      msg: "我是小猪课堂",
    };
  },
  computed: {},
  created() {
    console.log("我是mixin中的created生命周期函数");
  },
  mounted() {
    console.log("我是mixin中的mounted生命周期函数");
  },
  methods: {
    clickMe() {
      console.log("我是mixin中的点击事件");
    },
  },
};

3.2 Local mixing

After our public mixin is defined, the most important thing is how to use it. According to different business scenarios, we can divide it into two types: local mixing and global mixing. As the name suggests, local mixing is somewhat similar to the on-demand loading of components. That is, when the code in the mixin needs to be used, we will introduce it in the component chapter. Global mixing means that I can use the mixin in any component of the project.

Introducing mixin into the component is also very simple. Let’s slightly modify the App.vue component.

The code is as follows:

// src/App.vue
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <button @click="clickMe">点击我</button>
  </div>
</template>

<script>
import { mixins } from "./mixin/index";
export default {
  name: "App",
  mixins: [mixins],
  components: {},
  created(){
    console.log("组件调用minxi数据",this.msg);
  },
  mounted(){
    console.log("我是组件的mounted生命周期函数")
  }
};
</script>

The effect is as follows:

What are Mixins? Take you to understand Mixin mixing in Vue

上段代码中引入mixin的方法也非常简单,直接使用vue提供给我们的mixins属性:mixins:[mixins]。

通过上面的代码和效果我们可以得出以下几点:

  • mixin中的生命周期函数会和组件的生命周期函数一起合并执行。
  • mixin中的data数据在组件中也可以使用。
  • mixin中的方法在组件内部可以直接调用。
  • 生命周期函数合并后执行顺序:先执行mixin中的,后执行组件的。

问题提出:

这里我们就提出了一个问题:一个组件中改动了mixin中的数据,另一个引用了mixin的组件会受影响吗?

答案是不会的!

我们可以尝试一下:

在src下的components文件夹下新建demo组件,代码如下:

// src/components/demo.vue
<template>
  <div>mixin中的数据:{{ msg }}</div>
</template>
<script>
import { mixins } from "../mixin/index";
export default {
  mixins: [mixins],
};
</script>

然后在App.vue组件中引入demo组件,代码如下:

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <button @click="clickMe">点击我</button>
    <button @click="changeMsg">更改mixin数据</button>
    <demo></demo>
  </div>
</template>

<script>
import { mixins } from "./mixin/index";
import demo from "./components/demo.vue";
export default {
  name: "App",
  mixins: [mixins],
  components: { demo },
  created() {
    console.log("组件调用minxi数据", this.msg);
  },
  mounted() {
    console.log("我是组件的mounted生命周期函数");
  },
  methods: {
    changeMsg() {
      this.msg = "我是变异的小猪课堂";
      console.log("更改后的msg:", this.msg);
    },
  },
};
</script>

代码解释:

  • 我们在demo组件中引入了mixin,且使用了mixin中的msg数据。
  • 在App.vue中同样引入了mixin,且设置了点击事件更改msg
  • 点击按钮,更改msg,查看demo组件中显示是否有变化。

效果如下:

What are Mixins? Take you to understand Mixin mixing in Vue

可以看到我们在App.vue组件中更改了msg后,demo组件显示没有任何变化,所以这里我们得出结论:不同组件中的mixin是相互独立的!

3.3 全局混入

上一点我们使用mixin是在需要的组件中引入它,我们也可以在全局先把它注册好,这样我们就可以在任何组件中直接使用了。

修改main.js,代码如下:

import Vue from "vue";
import App from "./App.vue";
import { mixins } from "./mixin/index";
Vue.mixin(mixins);

Vue.config.productionTip = false;

new Vue({
  render: (h) => h(App),
}).$mount("#app");

然后把App.vue中引入mixin的代码注释掉,代码如下:

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <button @click="clickMe">点击我</button>
    <button @click="changeMsg">更改mixin数据</button>
    <demo></demo>
  </div>
</template>

<script>
// import { mixins } from "./mixin/index";
import demo from "./components/demo.vue";
export default {
  name: "App",
  // mixins: [mixins],
  components: { demo },
  created() {
    console.log("组件调用minxi数据", this.msg);
  },
  mounted() {
    console.log("我是组件的mounted生命周期函数");
  },
  methods: {
    changeMsg() {
      this.msg = "我是变异的小猪课堂";
      console.log("更改后的msg:", this.msg);
    },
  },
};
</script>

效果如下:

What are Mixins? Take you to understand Mixin mixing in Vue

可以发现效果上和局部混入没有任何区别,这就是全局混入的特点。

虽然这样做很方便,但是我们不推荐,来看看官方的一段话:

请谨慎使用全局混入,因为它会影响每个单独创建的 Vue 实例 (包括第三方组件)。大多数情况下,只应当应用于自定义选项,就像上面示例一样。推荐将其作为插件发布,以避免重复应用混入。

3.4 选项合并

上面的列子中我们仔细看会发现一个问题:mixin中定义的属性或方法的名称与组件中定义的名称没有冲突!

那么我们不禁会想,如果命名有冲突了怎么办?

我们使用git合并代码的时候经常会有冲突,有冲突了不要怕,我们合并就好了。这里的冲突主要分为以下几种情况:

(1)生命周期函数

确切来说,这种不算冲突,因为生命周期函数的名称都是固定的,默认的合并策略如下:

  • 先执行mixin中生命周期函数中的代码,然后在执行组件内部的代码,上面的例子其实就很好的证明了。

What are Mixins? Take you to understand Mixin mixing in Vue

(2)data数据冲突

当mixin中的data数据与组件中的data数据冲突时,组件中的data数据会覆盖mixin中数据,借用官方的一段代码:

var mixin = {
  data: function () {
    return {
      message: &#39;hello&#39;,
      foo: &#39;abc&#39;
    }
  }
}

new Vue({
  mixins: [mixin],
  data: function () {
    return {
      message: &#39;goodbye&#39;,
      bar: &#39;def&#39;
    }
  },
  created: function () {
    console.log(this.$data)
    // => { message: "goodbye", foo: "abc", bar: "def" }
  }
})

可以看到最终打印的message是组件中message的值,其它没有冲突的数据自然合并了。

(3)方法冲突

这种冲突很容易遇到,毕竟大家命名方法的名字很容易一样,这里同样借用官方的一段代码:

var mixin = {
  methods: {
    foo: function () {
      console.log(&#39;foo&#39;)
    },
    conflicting: function () {
      console.log(&#39;from mixin&#39;)
    }
  }
}

var vm = new Vue({
  mixins: [mixin],
  methods: {
    bar: function () {
      console.log(&#39;bar&#39;)
    },
    conflicting: function () {
      console.log(&#39;from self&#39;)
    }
  }
})

vm.foo() // => "foo"
vm.bar() // => "bar"
vm.conflicting() // => "from self"

上段代码中mixin和组件中都有conficting方法,但是最终在组件中调用时,实际调用的是组件中的conflicting方法。

当然,如果你要自定义合并规则也不是不可以,但是我觉得没有必要,项目中无需做这么复杂。

4. mixin的优缺点

从上面的例子看来,使用mixin的好处多多,但是凡是都有两面性,这里总结几点优缺点供大家参考:

4.1 Advantages

  • Improve code reusability
  • No need to transfer status
  • Easy to maintain, only need to modify one place

4.2 Disadvantages

  • Name conflict
  • If abused, it will be difficult to maintain later
  • It is difficult to trace the source , troubleshooting the problem is a little troublesome
  • Cannot repeat the code easily

Summary

mixin provides us with convenience but also brings disaster to us, so There are many times when it is not recommended to abuse it, but in some scenarios it is very appropriate to use it, so you have to make a choice based on yourself. So in many cases we need to consider whether to use public components or mixins.

(Learning video sharing: vuejs tutorial, web front-end)

The above is the detailed content of What are Mixins? Take you to understand Mixin mixing in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete