父子组件间传值
<div id="app">
<input type="text" name="name" v-model="inputValue">
<button @click="handleBtnCilck">提交</button>
<button @click="handleBtnClickEmpty">清空</button>
<ul>
<todo-item :content="item" :index="index" v-for="(item, index) in list" @delete="handleItemDelete">
</todo-item>
</ul>
</div>
<script>
//局部组件
var TodoItem = {
props: ['content','index'],
template: "<li @click='handleItemClick'>{{content}}</li>", //绑定一个click事件
methods: {
handleItemClick: function(){
//子组件向父组件传值,通过$emit方式向外触发事件,监听父组件的delete事件
this.$emit("delete", this.index);
}
}
}
var vm = new Vue({
el:'#app',
components:{ //通过对象注册局部组件
TodoItem:TodoItem
},
data:{
list:[],
inputValue:''
},
methods:{ //方法
handleBtnCilck: function(){
this.list.push(this.inputValue),
this.inputValue = ''
},
handleBtnClickEmpty: function(){
vm.$data.list = [],
this.inputValue = ''
},
handleItemDelete: function(index){ //接收子组件传过来的index
this.list.splice(index, 1) //点击一次,删除index 当前的一项
}
}
})
</script>