組件是可復用的 Vue 實例,且帶有一個名字
示例:
<div id="app">
<!-- 可重復使用-->
<my-component></my-component>
<my-component></my-component>
<my-component></my-component>
<my-component></my-component>
<my-component></my-component>
<my-component></my-component>
</div>
<script>
//組件模板中必須有一個根元素(父元素)
//全局組件 和Vue同級
Vue.component('my-component',{
template:`
<div>
<h1>嗨</h1>
<a href='#'>嘿</a>
<h2>哈</h2>
</div>
`
})
new Vue({
el:'#app'
})
</script>
//局部組件 在Vue實例中
<script>
new Vue({
el:'#app',
data:{
message:'hello Vue!'
},
//局部組件
components:{
'my-component':{
template:
`
<div>
<p>
<a href='#'>百度</a>
</p>
</div>
`
}
}
})
</script>
在Vue實例中data寫法是
new Vue({
el:'#app',
data:{
message:''
}
})
但是在組件中data必須是一個函數,data中的值還要return
Vue.component('my-component',{
data:function(){
return{
name:'123'
}
}
})
組件傳值(父子間傳值) 誰在誰中顯示,顯示的元素就是父元素,傳值用props:['']
<!-- 父子間傳值 props:['元素'] 父元素:誰在誰中顯示,顯示遲來的元素是父元素-->
<div id="app">
<father></father>
</div>
Vue.component('father',{
template:
`
<div>
<h1>這是父元素</h1>
<child v-bind:number='num'></child>
<button @click='jia'>點擊</button>
</div>
`,
data:function(){
return{
num:1
}
},
methods:{
jia:function(){
this.num++
}
}
})
Vue.component('child',{
props:['number'],
template:
//a標簽不能直接獲取num的值,顯示在父元素中的子元素綁定了子元素中的number元素=num
`
<div>
<p>這是子元素</p>
<a href='#'>{{number}}</a>
</div>
`
})
new Vue({
el:'#app'
})
案例一:刪除
效果圖:
body:
<div id="app">
<!--這里的自定義標簽很容易忘-->
<cont></cont>
</div>
js:
<script>
Vue.component('cont',{
template:
`
<div>
<input type='text' v-model='arrs'>
<button @click='tj'>添加</button>
<z v-bind:number='arr'></z>
</div>
`,
data:function(){
return{
arr:['banana','apple','orange'],
arrs:''
}
},
methods:{
tj:function(){
this.arr.push(this.arrs)
}
}
})
Vue.component('z',{
props:['number'],
template:
`
<ul>
<li v-for='(value,index) in number'>{{value}}
<button @click='sc'>刪除</button>
</li>
</ul>
`,
methods:{
sc:function(index){
this.number.splice(index,1)
}
}
})
new Vue({
el:'#app'
})
</script>
案例二:
效果圖:
<div id="app">
<cont></cont>
</div>
<script>
Vue.component('cont',{
template:
`
<div>
<h1>這是父元素</h1>
<top-title v-bind:sglb='tit'></top-title>
<list v-bind:listfruit='fruit'></list>
</div>
`,
data:function(){
return{
fruit:['apple','banana','orange'],
tit:'水果列表'
}
}
})
Vue.component('top-title',{
props:['sglb'],
template:
`
<div>
<h1>{{sglb}}</h1>
</div>
`
})
Vue.component('list',{
props:['listfruit'],
template:
`
<ul>
<li v-for='value in listfruit'>{{value}}</li>
</ul>
`
})
new Vue({
el:'#app'
})
</script>