Vue中父子组件之间信息的交互
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue入门</title>
<script src="vue.js"></script>
</head>
<body>
<div id="root">
<div>
<input v-model="learn"/>
<button @click="sub">提交</button>
</div>
<ul>
<todo-item
v-for="(item,index) of list"
:key="index"
<!--父组件通过属性的方式向子组件传递数据-->
:learn="item"
:index="index"
@delete="handle"
>
</todo-item>
</ul>
</div>
<script>
Vue.component('todo-item', {
//接收传递的数据
props: ['learn', "index"],
template: '<li @click="test1">{{learn}}</li>',
methods: {
test1: function () {
//子组件通过发布事件,父组件通过监听,已达成子组件向父组件传递信息的功能
this.$emit('delete', this.index);
}
}
})
new Vue
({
el: "#root",
data: {
learn: '',
list: []
},
methods: {
sub: function () {
this.list.push(this.learn);
this.learn = '';
},
handle: function (index) {
this.list.splice(index, 1);
}
}
})
</script>
</body>
</html>