基础组件实例:
var app = new Vue({
el:"#app",
data:{
}
})
注意:由于组件是可复用性的,名字相当于是自己自定义的标签,它也有着data、computed、watch、methods以及生命周期钩子(除el外)
在组件中,data必须是函数
可以通过prop向子组件传递数据
var app = new Vue({
el:"#app",
data:{
}
})
也可以结合普通的操作进行渲染
var app = new Vue({
el:"#app",
data:{
posts:[
{id:1,title:“My first blog”},
{id:2,title:“My second blog”},
{id:3,title:“My third blog”}
]
}
})
在组件的渲染中需要注意一个关键点,组件只能有一个根元素否则会进行报错(在下面组件最外层只有一个div)
var app = new Vue({
el:"#app",
data:{
posts:[
{id:1,title:“My first blog”,content:“
This is a msg
”},{id:2,title:“My second blog”,content:“
This is a msg
”},{id:3,title:“My third blog”,content:“
This is a msg
”}]
}
})
还需要进行key的绑定,会将警告消除
按照上述的方法进行编码会写上大量的代码如下:
var app = new Vue({
el:"#app",
data:{
posts:[
{
id:1,
title:“My first blog”,
content:“
This is a msg
”,publishedAt:“2019-8-14”,
comments:[
]
},
{id:2,title:“My second blog”,content:“
This is a msg
”},{id:3,title:“My third blog”,content:“
This is a msg
”}]
}
})
需要对代码进行重构:相当于整个json的传入,然后进行模板的遍历循环渲染
var app = new Vue({
el:"#app",
data:{
posts:[
{
id:1,
title:“My first blog”,
content:“
This is a msg
”,publishedAt:“2019-8-14”,
comments:[
]
},
{id:2,title:“My second blog”,content:“
This is a msg
”},{id:3,title:“My third blog”,content:“
This is a msg
”}]
}
})
通过事件向父级组件发送消息
var app = new Vue({
el:"#app",
data:{
posts:[
{
id:1,
title:“My first blog”,
content:“
This is a msg
”,publishedAt:“2019-8-14”,
comments:[
]
},
{id:2,title:“My second blog”,content:“
This is a msg
”},{id:3,title:“My third blog”,content:“
This is a msg
”}],
postFontSize:1,
},
methods:{
changeFontSize:function(count){
this.postFontSize+=count;
}
}
})
重点:在子组件中调用父组件的方法需要用到 e m i t 方 法 , 然 后 将 emit方法,然后将 emit方法,然后将emit定义的方法名称和父组件的方法进行绑定
var app = new Vue({
el:"#app",
data:{
posts:[
{
id:1,
title:“My first blog”,
content:“
This is a msg
”,publishedAt:“2019-8-14”,
comments:[
]
},
{id:2,title:“My second blog”,content:“
This is a msg
”},{id:3,title:“My third blog”,content:“
This is a msg
”}],
postFontSize:1,
},
methods:{
changeFontSize:function(count){
this.postFontSize+=count;
}
}
})
使用事件抛出一个值, e m i t 中 再 加 入 一 个 参 数 , 上 面 的 传 入 参 数 为 emit中再加入一个参数,上面的传入参数为 emit中再加入一个参数,上面的传入参数为event
var app = new Vue({
el:"#app",
data:{
posts:[
{
id:1,
title:“My first blog”,
content:“
This is a msg
”,publishedAt:“2019-8-14”,
comments:[
]
},
{id:2,title:“My second blog”,content:“
This is a msg
”},{id:3,title:“My third blog”,content:“
This is a msg
”}],
postFontSize:1,
},
methods:{
changeFontSize:function(count){
console.log(“event”,count);
this.postFontSize+=count;
}
}
})
通过插槽分发内容
var app = new Vue({
el:"#app",
data:{
message:“hello world”
}
})
在下面需要注意的是,通过is事件绑定的是组件的模板渲染效果和组件里的子组件或者div等没有关系,将组件的名称统一写为component进行切换渲染
Vue.component(‘tab02’,{
template:`
var app = new Vue({
el:"#app",
data:{
currentTab:“tab02”
}
})
最后注意某些html元素内部是有严格限制的,如li,tr标签等
但是如果从template的字符串、vue的单文件组件、script里的来源是不受限制的