前言
// 定义一个混入对象
var myMixin = {
created: function () {
this.hello()
},
methods: {
hello: function () {
console.log('hello from mixin!')
}
}
}
// 定义一个使用混入对象的组件
var Component = Vue.extend({
mixins: [myMixin]
})
var component = new Component() // => "hello from mixin!"
合并
var mixin = {
data: function () {
return {
message: 'hello',
foo: 'abc'
}
},
created: function () {
console.log('混入对象的钩子被调用')
}
}
new Vue({
mixins: [mixin],
created: function () {
console.log('组件钩子被调用');
console.log(this.$data)
// => { message: "goodbye", foo: "abc", bar: "def" }
},
data: function () {
return {
message: 'goodbye',
bar: 'def'
}
}
})
// => "混入对象的钩子被调用"
// => "组件钩子被调用"
实践
var myMixin = {
created() {
// 发起异步请求
Vue.axios.get(api).then((response) => {
console.log("1234")
})
}
}
// 定义一个使用混入对象的组件A
var ComponentA = Vue.extend({
mixins: [myMixin]
})
var componenta = new ComponentA() // => "1234"
// 定义一个使用混入对象的组件B
var ComponentB = Vue.extend({
mixins: [myMixin]
})
var componentb = new ComponentB() // => "1234"
和插件一起使用
// Plugin.js
function Plugin() {
}
// 该对象具备install函数
Plugin.install = function (Vue) {
// mixin
Vue.mixin({
created() {
console.log('1234')
}
})
}
export default Plugin;
// main.js
import Plugin from './Plugin';
Vue.use(Plugin);
始发于微信公众号: 腾讯DeepOcean