Vue混入挂载

最近在学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>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值