Vue的Mixins

Vue的Mixins

混入 (mixin) 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项。

mixins->show.js

里面可以写script标签中export default里面的所有内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 定义复用的代码
export const show = {
data() {
return {
msg: "我是共用的数据"
}
},
methods:{
show() {
console.log("我是共用方法")
}
},
created() {
console.log("组件被创建了")
}
}

当组件和混入对象含有同名选项时,这些选项将以恰当的方式进行“合并”。

比如,数据对象在内部会进行递归合并,并在发生冲突时以组件数据优先。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<template>
<div>
<h1>{{msg}}</h1>
<button @click="show">点击调用show的方法</button>
</div>
</template>

<script>
import {show} from '../mixins/show'
export default {
name: 'ComponentA',
mixins: [show],
data() {
return {

}
}
}
</script>

<style lang="scss" scoped>

</style>

同名钩子函数将合并为一个数组,因此都将被调用。另外,混入对象的钩子将在组件自身钩子之前调用。

image-20220903105745790

值为对象的选项,例如 methodscomponentsdirectives,将被合并为同一个对象。两个对象键名冲突时,取组件对象的键值对。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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"

全局混入

image-20220903110132678

官网介绍参考:https://v2.cn.vuejs.org/v2/guide/mixins.html


Vue的Mixins
http://example.com/2022/09/03/Mixins/
作者
Deng ErPu
发布于
2022年9月3日
许可协议