vue的混入 - Mixins
一、mixins的介绍
混入 (mixins):是一种分发 Vue 组件中可复用功能的非常灵活的方式。混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被混入该组件本身的选项。
mixins:则是在引入组件之后与组件中的对象和方法进行合并,相当于扩展了父组件的对象与方法,可以理解为形成了一个新的组件。
二、mixins的使用
1. 创建混入对象
在src目录下创建一个 mixins 文件夹,文件夹下新建一个 hello.js 文件,作为之后的 混入对象 。前面我们说了 mixins 是一个 js对象 ,所以应该以对象的形式来定义 hello.js 。在对象中我们可以和 vue组件 一样来定义我们的 data、components、methods 、created、computed 等属性,并通过 export default 导出该对象。
export default {
data () {
return {
msg: 'Welcome to Your Minins',
content: '我是mixins的内容',
num: 1
}
},
created () {
this.init()
},
methods: {
init () {
console.log('mixins')
},
sayHello () {
alert('Hello mixins')
}
}
}
2. 引入混入对象
在需要调用的组件中引入 hello.js 文件,然后通过 mixins:[文件名] 来使用就可以了:
HelloWorld.vue:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<div>{{ content }}</div>
<button @click="sayHello">点击</button>
</div>
</template>
<script>
// 引入hello.js
import hello from '@/mixins/hello.js'
export default {
name: 'HelloWorld',
// 引入混入对象
mixins: [hello],
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
</script>
三、mixins的特点
1. 方法和参数在各组件中不共享
如:混入对象中有一个 num : 1 的变量,在 HelloWorld.vue 中改变num值为 2 ,这时候在组件 index.vue 中获取这个值,拿到的还是 1,还是混入对象里的初始值,数据不共享。
HelloWorld.vue:
<script>
import hello from '@/mixins/hello.js'
export default {
name: 'HelloWorld',
mixins: [hello],
created () {
this.num++
}
}
</script>
index.vue:
<template>
<div class="index">
<div>{{num}}</div>
</div>
</template>
<script>
import hello from '@/mixins/hello.js'
export default {
name: 'index',
mixins: [hello]
}
</script>
index.vue页面显示为num初始值:1
2. mixins的合并冲突
- 值为 对象(components、methods、computed、data) 的选项,混入组件时选项会被合并,键冲突时 优先组件,组件中的键会覆盖混入对象的;
如:混入对象中的 msg,sayHello 方法,混入组件时遇到同名的变量和方法,就会被组件覆盖。
HelloWorld.vue:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<div>{{ content }}</div>
<button @click="sayHello">点击</button>
</div>
</template>
<script>
import hello from '@/mixins/hello.js'
export default {
name: 'HelloWorld',
mixins: [hello],
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
methods: {
sayHello () {
alert('Hello world')
}
}
}
</script>
- 值为 函数(created、mounted) 的选项,混入组件时选项会被 合并调用,混合对象里的钩子函数在组件里的钩子函数之前调用。
如:混入对象中的created 方法和组件中的created 方法都会执行,但是混入对象中的created 方法会优先执行。
HelloWorld.vue:
import hello from '@/mixins/hello.js'
export default {
name: 'HelloWorld',
mixins: [hello],
created () {
console.log('hello world')
}
}
</script>
3. 与vuex的区别
- vuex:用来做状态管理的,里面定义的变量在每个组件中均可以使用和修改,在任一组件中修改此变量的值之后,其他组件中此变量的值也会随之修改;
- mixins:可以定义共用的变量,在每个组件中使用,引入组件中之后,各个变量是相互独立的,值的修改在组件中不会相互影响。
4. 与公共组件的区别
组件:在父组件中引入组件,相当于在父组件中给出一片独立的空间供子组件使用,然后根据props来传值,但本质上两者是相对独立的;
mixins:在引入组件之后与组件中的对象和方法进行合并,相当于扩展了父组件的对象与方法,可以理解为形成了一个新的组件。
更多详细内容请参考: Vue — 详解mixins混入使用