创建组件的两种方法小结
1.全局注册
2.局部注册
var child=Vue.extend({})
var parent=Vue.extend({})Vue.extend() 全局方法 生成构造器,创建子类
使用基础 Vue 构造器,创建一个“子类”。
这样写非常繁琐。于是vue进行了简化
使用Vue.component()直接创建和注册组件:
Vue.component(id,options) 全局方法 用来注册全局组件
id 是string类型,即是注册组件的名称
options 是个对象
// 全局注册,my-component1是标签名称
Vue.component('my-component1',{
template: '<p>This is the first component!</p>'
})
var vm1 = new Vue({
el: '#app1'
})Vue.component()的第1个参数是标签名称,第2个参数是一个选项对象,使用选项对象的template属性定义组件模板。
使用这种方式,Vue在背后会自动地调用Vue.extend()。
在选项对象的components属性中实现局部注册:
var vm2 = new Vue({
el: '#app2',
components: {
// 局部注册,my-component2是标签名称
'my-component2': {
template: '<p>This is the second component!</p>'
},
// 局部注册,my-component3是标签名称
'my-component3': {
template: '<p>This is the third component!</p>'
}
}
})==局部注册都放在选项对象中创建==
注意:这里是components,里面可以定义多个组件。
简化后是这样的写法
<body>
<p id='box'>
<parent>
</parent>
</p>
<script src='js/vue.js'></script>
<script>
Vue.component('parent',{
template:`<p><h1>我是父组件</h1><child></child></p>`,
components:{
'child':{
template:`<h1>我是子组件</h1>`
}
}
})
new Vue({
el:'#box'
})
</script>
</body>注册一个parent的父组件。然后在父组件的选项对象中注册一个child的子组件。将子组件child的标签写到父组件parent的template里面。
页面上的样式结构就是
<p> <h1>我是父组件</h1> <h1>我是子组件</h1> </p>
注意:用局部注册的子组件不能单独直接使用!
标签挂在p里,会报错
<p id='box'> <child></child> </p>
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
在angular中基于ng-alain如何定义自己的select组件?
在vue中如何实现watch监听对象及对应值的变化
如何解决Vue不能检测数组或对象变动方面问题?
Copyright © 2019- 99spj.com 版权所有 湘ICP备2022005869号-5
违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务