前言
在上一節裏,我們已經寫了一個todoList,下面我將用全局組件和局部組件化把todoList拆分。
1.父組件向子組件傳值
全局組件
父組件中相關代碼
Vue.component(
"TodoList",{
props:['content'],
template:"<li>{{content}}</li>"
}
)
子組件中相關代碼
<!-- 注意不要忘記加v-bind -->
<todo-list v-for="item in list" v-bind:content="item"></todo-list>
解析:
- 先定義一個全局化的組件TodoList,template代表模板,props代表接收從子組件傳來的數據,裏面是數組的形式。
注意事項:
- . 要使用**v-bind:**來綁定數據
局部組件
父組件相關代碼
// 局部組件化
var todoList = {
props: ['content'],
template: "<li>{{content}}</li>"
}
new Vue中添加components屬性
components:{
todoList:todoList
},
注意:
- components應該是複數
子組件向父組件傳值
當點擊刪除的時候就要用到這個啦,,感覺很麻煩,需要注意的地方也很多。
- 首先在template模板中加入點擊事件。
template: "<li @click='handleDelete'>{{content}}</li>",
- 在子組件裏把handleDelete實現,這裏使用this.$emit(“deleteindex”,this.index) 函數,傳入父組件中。
handleDelete:function(){
// alert("子組件"+this.index)
this.$emit("deleteindex",this.index)
}
- 把todo-list補充完整。
<todo-list v-for="(item,index) in list"
v-bind:content="item" :index="index"
@deleteindex="delete1"
></todo-list>
4.最後在父組件中實現delete1,實現刪除功能。
delete1: function(index){
this.list.splice(index,1)
}
注意:
- @後面的一定不要有大寫的字母,否則會報錯
- v-bind: 可以簡寫爲 :
寫於2020年情人節,祝天下有情人終成眷屬