组件之间数据传递
父传子:在父组件通过 v-bind 属性绑定传递
<todo-item v-for="item in list" :key="iten" v-bind:content='item' v-bind:index="index" ></todo-item>
子组件通过props接收父组件传过来的数据
props: [
'content', 'index'
],
子传父:在子组件通过 v-on 事件绑定触发
//1
template: "<li v-on:click='handleItemDel'>{{content}}</li>",
//2
methods:{
//点击子组件时,会向外触发一个deleteItem事件
handleItemDel(){
this.$emit('delete',this.index)
}
}
//3在父组件创建子组件的同时,可以去监听这个delete事件
<todo-item v-for="item in list" :key="iten" v-bind:content='item' v-bind:index="index" @delete="handleItemDelete"></todo-item>
//通过下标实现删除项
handleItemDelete(index) {
console.log(index);
this.list.splice(index, 1)
}
父传子 & 子传父 完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3使用组件化思想修改TodoList</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="inputValue">
<button v-on:click='handleBtn'>提交</button>
<ul>
<todo-item v-for="(item,index) in list" :key="index" v-bind:content='item' v-bind:index="index"
@delete="handleItemDelete"></todo-item>
</ul>
</div>
<script>
// 全局组件
// Vue.component("TodoItem", {
// props: [
// 'content'
// ],
// template: "<li>{{content}}</li>"
// })
// 局部组件(需要注册到根Vue实例里)
var TodoItem = {
props: [
'content', 'index'
],
template: "<li v-on:click='handleItemDel'>{{content}}</li>",
methods: {
//点击子组件时,会向外触发一个delete事件
handleItemDel() {
this.$emit('delete', this.index)
}
}
}
// 父组件
var app = new Vue({
el: '#app',
// 注册局部组件
components: {
TodoItem
},
data: {
list: [],
inputValue: ''
},
methods: {
handleBtn() {
console.log(app.$data.inputValue);
console.log(this.inputValue);
this.list.push(app.$data.inputValue)
this.inputValue = ''
},
handleItemDelete(index) {
console.log(index);
this.list.splice(index, 1)
}
},
})
</script>
</body>
</html>
网友评论