父组件和子组件间主要通过发布订阅模式进行通信的
父组件向子组件传值是通过属性的形式传递的,子组件可通过this.$emit()方法向父组件发布消息,父组件监听子组件的事件实现交互
父组件
<template>
<div id="app">
<div>
<input type="text" v-model="inputData"/>
<button @click="handleSubmit">提交</button>
</div>
<ul>
<todo-list v-for="(item,index) of list"
:key="index"
:content="item"
@deleteItem="handleDelete"
:index="index">
</todo-list>
</ul>
</div>
</template>
<script>
import TodoItem from './components/TodoItem'
export default {
components: {
'todo-list': TodoItem
},
data () {
return {
inputData: '输入的数据',
list: []
}
},
methods: {
handleSubmit () {
this.list.push(this.inputData),
this.inputData = ''
},
handleDelete (index) {
this.list.splice(index,1)
}
}
}
</script>
<style lang="scss">
#app {
text-align: center;
}
</style>
子组件
<template>
<li>{{content}} <span @click="handleDelete">删除{{index}}</span></li>
</template>
<script>
export default {
props: ['content','index'],
name: 'TodoItem',
methods:{
handleDelete(){
this.$emit('deleteItem',this.index)
}
}
}
</script>
<style scoped>
</style>