话不多说,先上todoList效果与完整代码.
效果:
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>TODOLIST</title>
<script type="text/javascript" src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
<h1>TODOLIST</h1>
<br />
<input type="text" placeholder="请输入待办事项" v-model="inputValue" />
<Button @click="addHandler">提交</Button>
<hr>
<h2>未完成</h2>
<ul>
<todo-item v-for="(item,index) in list" :key="index" :item="item" :index="index"
@delete="deleteHandlerByParent" @finish="finishHandlerByParent" />
</ul>
<hr>
<h2>完成</h2>
<ul>
<finish-item v-for="(item,index) in list1" :key="index" :item="item"
@delete="deleteFinishHandlerByParent" />
</ul>
</div>
<script>
var TodoItem = {
props: ['item', 'index'],
template: "<li>{{item}} <button @click='finishHandlerBySon'>完成</button> <button @click='deleteHandlerBySon'>删除</button></li>",
methods: {
deleteHandlerBySon: function () {
this.$emit('delete', this.index);
},
finishHandlerBySon: function () {
this.$emit('finish', this.index);
}
}
}
var FinishItem = {
props: ['item', 'index'],
template: "<li>{{item}} <button @click='deleteFinishHandlerBySon'>删除</button></li>",
methods: {
deleteFinishHandlerBySon: function () {
this.$emit('delete', this.index);
}
}
}
var app = new Vue({
el: '#app',
components: {
TodoItem: TodoItem,
FinishItem: FinishItem,
},
data: {
list: [],
inputValue: "",
list1: [],
},
methods: {
addHandler: function () {
this.list.push(this.inputValue);
this.inputValue = "";
},
deleteHandlerByParent: function (index) {
this.list.splice(index, 1);
},
finishHandlerByParent: function (index) {
this.list1.push(this.list[index]);
this.list.splice(index, 1);
},
deleteFinishHandlerByParent: function (index) {
this.list1.splice(index, 1);
}
}
});
</script>
</body>
</html>
首先我们要明确概念:
var app = new Vue();
,这个app就是父组件,因为它挂载的是整个div,所以div内的值都可以算是父组件的值.
components: { TodoItem: TodoItem, FinishItem: FinishItem, }
,TodoItem,finishItem都是子组件.
一.父组件传值给子组件
需求: 我们在输入框中输入值并点击提交,输入框中的值会赋给inputValue
,这个inputValue
很明显就是父组件的值,我们要把这个父组件的inputValue
传给我们自定义的组件todoItem
(子组件),然后在todoItem中显示出来.
props: ['item', 'index']
.通过props
属性,在子组件中声明来自父组件的值- (❤️)
:item="item" :index="index"
.将父组件的值传给刚刚在子组件中声明的值. - 然后我们在
template
中就可以通过插值表达式获取到了{{item}}
,{{index}}
二.子组件传值给父组件
需求:刚刚我们完成了父组件传值给子组件,现在我们在未完成中可以看到我们刚刚输入的待办事项.然后我们点击未完成的待办事项的完成按钮,将未完成的待办事项添加到完成.
-
<button @click='finishHandlerBySon'>完成</button>
. 点击完成按钮,进入子组件的finishHandlerBySon
方法. -
(❤️)
finishHandlerBySon: function () { this.$emit('finish', this.index); }
.在子组件中通过emit
发送finish
事件并带上子组件的值index
. -
(❤️)
@finish="finishHandlerByParent"
. 父组件监听finish事件
,并触发finishHandlerByParent
方法. -
finishHandlerByParent: function (index) { this.list1.push(this.list[index]); this.list.splice(index, 1); }
.在finishHandlerByParent(index)
中通过形参index
我们获取子组件中传递过来的值index
.
父子组件之间的通信总结来说就是:
父传子:props
子传父:emit
建议自己动手实现完整的todolist功能,这样对父子组件的通信就会很熟练了!!!?