父组件:
<template>
<div id="app">
<img src="./assets/logo.png">
<router-view/>
<input type="text" v-model="todoValue">
<button @click="handlBtnClick">提交</button>
<ul>
<to-do-item v-bind:content="item"
v-bind:index="index"
v-for="(item,index) in lists"
@delete="handelItemDelete "
>
{{item}}
</to-do-item>
</ul>
</div>
</template>
<script>
import ToDoItem from './components/TodoItem'
export default {
name: 'App',
data ()
{
return {
todoValue: '',
lists: ['apple','banana','orange']
}
},
components: {
ToDoItem
},
methods: {
handlBtnClick ()
{
this.lists.push (this.todoValue);
this.todoValue = ''
},
handelItemDelete(index){
this.lists.splice(index,1)
}
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
子组件:
<template>
<div>
<li @click="handleClick" >{{content}}</li>
</div>
</template>
<script>
export default {
name: "TodoItem",
props:['lists','content','index'],
data(){
return {
}
},
methods:{
handleClick(){
this.$emit('delete',this.index)
}
}
}
</script>
<style scoped>
ul, li {
list-style: none;
}
</style>
子组件获取父组件的数据通过props:父组件可以通过bind方法将数据传递给子组件;子组件通过$emit传递事件,同时可以传递子组件的数据;在父组件监听子组件的事件,通过监听获取子组件的数据。