最近在学Vue,看到混入这个概念,觉得挺有趣的。Vue教程——混入的例子只是输出到控制台。
// 定义一个混入对象
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!"
但是如果混入对象包含模板(template),需要在HTML里显示具体内容的时候,却不能直接用。
// 定义一个混入对象
var myMixin = {
template: '<p>test</P>' //<---追加
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!"
网上查找到两种方式可以挂载到HTML。
一、
//需要再加以下一行代码
component.$mount('Component')
然后就可以在HTML中使用了
<div id="demo">
<Component></Component>
</div>
注意此处使用的标签名是后面的组件类'Component'而不是前面的实例component
并且在用mount()的时候一定要用引号''括起来而不可以直接作为参数。
//或者也可以加以下一行代码
component.$mount('#demo')
然后就可以在HTML中使用了,不需要使用组件名儿直接挂载到对应的元素(参照Vue.extend( options )I)
<div id="demo"></div>
二、
在Vue实例调用的时候
new Vue({
el:'#demo',
mixins: [myMixin]
})
然后就可以在HTML中使用了
<div id="demo">
<Component></Component>
</div>