Vue如何使用混合Mixins和插件开发

官网:混合 (mixins) 是一种分发 Vue 组件中可复用功能的非常灵活的方式。混合对象可以包含任意组件选项。以组件使用混合对象时,所有混合对象的选项将被混入该组件本身的选项。 个人:混入就是用来对vue组件中的公共部分,包括数据对象、钩子函数、方法等所有选项,进行提取封装,以达到代码的复用,混合用处挺大的,然我们来看看实际用法。

基础用法

// 这是在main.js根文件中使用,在组中使用也是一样
import Vue from ‘vue’;
var mixin = {
data() {
return {
name: ‘www.vipbic.com’,
author: ‘羊先生’
}
},
created: function() {
console.log(‘Website:’ + this.name)
},
methods: {
foo: function() {
console.log(‘作者:’ + this.author)
},
conflicting: function() {
console.log(‘from mixin’)
}
}
}

new Vue({
mixins: [mixin],
render: h => h(App),
created() {
let option = this.$options.doNotInit
console.log(‘option:’, );
this.foo()
}
}).$mount(‘#app’)

// 在组建中使用

var mixin = {
data() {
return {
name: ‘www.vipbic.com’,
author: ‘羊先生’
}
},
created: function() {
console.log(‘Website:’ + this.name)
},
methods: {
foo: function() {
console.log(‘作者:’ + this.author)
}
}
}
export default {
mixins: [mixin],
created(){
this.foo()
}
}

效果如下,都一样,可以看出混合mixins中的created高于组件created执行优先级

image.png

全局注册

main.js中直接注册

import Vue from ‘vue’;
var mixin = {
data() {
return {
name: ‘www.vipbic.com’,
author: ‘羊先生’
}
},
created: function() {
console.log(‘Website:’ + this.name)
},
methods: {
foo: function() {
console.log(‘作者:’ + this.author)
}
}
}

Vue.mixin(mixin)
new Vue({
render: h => h(App)
}).$mount(‘#app’)

效果如下,我们先不调用,看看控制台是否有打印结果,可以发现我们并未调用,就打印了两次,按照大家常规考虑可能会想到执行一次,是正常的,即初始化一次,但却执行了两次

image.png

如何解决执行两次

我在网上看到都是这么做的,都说是从官网上看到的,但是我在官网上并没有看到,不过的确能解决问题

var mixin = {
data() {
return {
name: ‘www.vipbic.com’,
author: ‘羊先生’
}
},
created: function() {
let option = this.$options.doNotInit;
console.log(option) // 第一次执行 true 第二次为 undefined
if (!option) {
// 可以放置一些你的逻辑,比如一开始就要调用的方法
console.log(‘Website:’ + this.name)
}
},
methods: {
foo: function() {
console.log(‘作者:’ + this.author)
},
}
}

Vue.mixin(mixin);
new Vue({
doNotInit: true, // 添加一个状态
render: h => h(App),
}).$mount(‘#app’)

效果如下

image.png

发表评论

邮箱地址不会被公开。 必填项已用*标注