今天学习了简单的父子组件传值的案例。
以下是完整代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>父子组件简传值</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="inputValue">
<button type="button" v-on:click="hadnleBtnClick">提交</button>
<ul>
<todo-item v-bind:content="item" v-for="(item,index) in list" @delete="handleItemDelete" v-bind:index="index">
</todo-item>
</ul>
</div>
<script>
//全局组件写法
// Vue.component("TodoItem", {
// props: ['content'],
// template: "<li>{{content}}</li>",
// })
//局部组件写法
var TodoItem = {
props: ['content', 'index'],
template: "<li @click='handleItemClick'>{{content}}</li>",
methods: {
handleItemClick: function() {
this.$emit("delete", this.index); //通过$emit向外触发事件
}
}
}
var app = new Vue({
el: "#app",
components: {
TodoItem: TodoItem
},
data: {
list: ['第一节课内容', '第二节课内容'],
// list: [],
inputValue: ''
},
methods: {
hadnleBtnClick: function() {
this.list.push(this.inputValue);
this.inputValue = '';
},
handleItemDelete: function(index) {
this.list.splice(index, 1)
}
}
})
</script>
</body>
</html>
1.通过属性传值;
2.子组件通过 this.$emit("delete", this.index) 向外触发事件;
3.父组件通过@delete来监听子组件的事件;
4.通过index参数来触发改变哪一项;
5.通过handleItemDelete 来删除子项;