Vue中通过props和$emit实现父子组件的通信。
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>todolist</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<div id="root">
<div>
<input type="text" v-model="inputValue">
<button @click="handleSubmit">Submit</button>
<ul>
<todo-item v-for="(item, index) in list" :key="index" :content="item" :index="index"
@delete="handleDelete"></todo-item>
</ul>
</div>
</div>
<script>
//创建一个全局组件 component todo-item
Vue.component('todo-item', {
props: ['content', 'index'],
template: '<li @click="handleClick">{{content}}</li>',
methods: {
handleClick: function () {
//子组件向外部传递一个delete事件
this.$emit('delete', this.index)
}
}
})
new Vue({
el: '#root',
data() {
return {
inputValue: '',
list: []
}
},
methods: {
handleSubmit: function () {
if (this.inputValue !== '') {
this.list.push(this.inputValue)
} else {
alert('The input cannot be null')
}
this.inputValue = ''
},
handleDelete: function (index) {
this.list.splice(index, 1)
}
}
})
</script>
</body>
</html>