Home >Web Front-end >Vue.js >What are Mixins? Take you to understand Mixin mixing in Vue
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!
#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]
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.
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:
We understand the concept of Mixin, so how to use it? This is our focus.
Next, our mixin will be demonstrated in the Vue2.x scaffolding project.
Use Vue-cli to initialize the simplest project:
The code is as follows:
// src/mixin/index.js export const mixins = { data() { return {}; }, computed: {}, created() {}, mounted() {}, methods: {}, };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中的点击事件"); }, }, };
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:
上段代码中引入mixin的方法也非常简单,直接使用vue提供给我们的mixins属性:mixins:[mixins]。
通过上面的代码和效果我们可以得出以下几点:
问题提出:
这里我们就提出了一个问题:一个组件中改动了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>
代码解释:
效果如下:
可以看到我们在App.vue组件中更改了msg后,demo组件显示没有任何变化,所以这里我们得出结论:不同组件中的mixin是相互独立的!
上一点我们使用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>
效果如下:
可以发现效果上和局部混入没有任何区别,这就是全局混入的特点。
虽然这样做很方便,但是我们不推荐,来看看官方的一段话:
请谨慎使用全局混入,因为它会影响每个单独创建的 Vue 实例 (包括第三方组件)。大多数情况下,只应当应用于自定义选项,就像上面示例一样。推荐将其作为插件发布,以避免重复应用混入。
上面的列子中我们仔细看会发现一个问题:mixin中定义的属性或方法的名称与组件中定义的名称没有冲突!
那么我们不禁会想,如果命名有冲突了怎么办?
我们使用git合并代码的时候经常会有冲突,有冲突了不要怕,我们合并就好了。这里的冲突主要分为以下几种情况:
(1)生命周期函数
确切来说,这种不算冲突,因为生命周期函数的名称都是固定的,默认的合并策略如下:
(2)data数据冲突
当mixin中的data数据与组件中的data数据冲突时,组件中的data数据会覆盖mixin中数据,借用官方的一段代码:
var mixin = { data: function () { return { message: 'hello', foo: 'abc' } } } new Vue({ mixins: [mixin], data: function () { return { message: 'goodbye', bar: 'def' } }, created: function () { console.log(this.$data) // => { message: "goodbye", foo: "abc", bar: "def" } } })
可以看到最终打印的message是组件中message的值,其它没有冲突的数据自然合并了。
(3)方法冲突
这种冲突很容易遇到,毕竟大家命名方法的名字很容易一样,这里同样借用官方的一段代码:
var mixin = { methods: { foo: function () { console.log('foo') }, conflicting: function () { console.log('from mixin') } } } var vm = new Vue({ mixins: [mixin], methods: { bar: function () { console.log('bar') }, conflicting: function () { console.log('from self') } } }) vm.foo() // => "foo" vm.bar() // => "bar" vm.conflicting() // => "from self"
上段代码中mixin和组件中都有conficting方法,但是最终在组件中调用时,实际调用的是组件中的conflicting方法。
当然,如果你要自定义合并规则也不是不可以,但是我觉得没有必要,项目中无需做这么复杂。
从上面的例子看来,使用mixin的好处多多,但是凡是都有两面性,这里总结几点优缺点供大家参考:
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!