子向父传递组件:
示例:
在通过点击列表元素后自动删除所点击的列表。
先放完整的代码先:
<!DOCTYPE html>
<html>
<head>
<title>TodoList</title>
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="inputvalue">
<button v-on:click="handleBtnClick">提交</button>
<ul>
<todo-item v-bind:content="item" v-bind:index="index" v-for="(item,index) in List" v-on:delete="handleItemDelete"></todo-item>
</ul>
</div>
</body>
<script>
var TodoItem = {
props: ['content', 'index'],
template: "<li v-on:click='handleDeleteClick'>{{content}}</li>",
methods: {
handleDeleteClick: function() {
this.$emit('delete', this.index)
}
}
}
var app = new Vue({
el: "#app",
data: {
List: [],
inputvalue: ''
},
methods: {
handleBtnClick: function() {
this.List.push(this.inputvalue)
this.inputvalue = ''
},
handleItemDelete: function(index){
this.List.splice(index, 1)
}
},
components: {
TodoItem: TodoItem
}
})
</script>
</html>
1.子组件建立点击事件发生数据变更函数触发:
$emit()中的第一个参数是事件名(名字随便取),第二个是传出的参数
var TodoItem = {
props: ['content', 'index'],
template: "<li v-on:click='handleDeleteClick'>{{content}}</li>",
methods: {
handleDeleteClick: function() {
this.$emit('delete', this.index)
}
}
}
2.父组件通过监听delete(根据$emit中的第一个参数名字来决定)
<todo-item v-bind:content="item" v-bind:index="index" v-for="(item,index) in List" v-on:delete="handleItemDelete"></todo-item>
3.根据监听delete的函数进行数据处理完成子-父传递数据的过程:
handleItemDelete: function(index){
this.List.splice(index, 1)
}
对了 v-bind==:
v-on==@ 也就是说
v-bind:content="item" == :content="item"
v-on:click="handleBtnClick == @click="handleBtnClick