父组件向子组件传递数据时,在子组件中props如何获取
通过事件监听watch
1.在父组件中
<template>
<div>
<child :books="books"></child>
<label for="">id:</label><input type="text" v-model="id" />
<label for="">name:</label><input type="text" v-model="name" />
<button @click="add">添加</button>
</div>
</template>
<script>
import child from "./child.vue";
export default {
name: "",
data() {
return {
books: [
{ id: 1, name: "王苏" },
{ id: 2, name: "代码" },
],
id: "",
name: "",
};
},
methods: {
add() {
this.books.push({ id: this.id, name: this.name });
},
},
components: {
child,
},
};
</script>
<style></style>
2.在子组件中
<template>
<div>
<ul v-for="item in list" :key="item.id">
<li>Id:{{item.id}}</li>
<li>name:{{item.name}}</li>
</ul>
<button @click="del">删除</button>
<son></son>
</div>
</template>
<script>
import son from "./son.vue"
export default {
name:'',
props:{
books:{
type:Array,
default:[]
}
},
data () {
return {
list:[]
}
},
methods: {
del(){
this.list.pop()
}
},
watch:{
books:function(newVal,oldVal){
console.log(newVal)
console.log(oldVal)
this.list=newVal
}
},
components: {
son
}
}
</script>
<style>
</style>
在子组件中利用watch的事件监听,通过监听props中传过来的属性