基本数据类型
所有的 prop 都使得其父子 prop 之间形成了一个单向下行绑定:父级 prop 的更新会向下流动到子组件中,但是反过来则不行。这样会防止从子组件意外变更父级组件的状态,从而导致你的应用的数据流向难以理解。
1. 子组件抛出自定义事件
// 子组件抛出自定义事件修改props接收的基本数据类型
changeCount() {
this.$emit('update:changeCount',100)
},
// 父组件注册自定义事件
// $event 访问到被抛出的值,也可以自己实现回调函数
<TestSon :count="count" @update:changeCount="count = $event"></TestSon>
2. .sync修饰符
.sync相当于以上方式的语法糖
// this.$emit('update:prop接收的值',val)
changeCount() {
this.$emit('update:count',100)
},
// 相当于简化了父组件注册自定义事件这一步骤,在子组件中直接修改
<TestSon :count.sync="count"></TestSon>
引用数据类型
对象和数组是通过引用传入的,所以对于一个数组或对象类型的 prop 来说,在子组件中改变变更这个对象或数组本身将会影响到父组件的状态。
代码
父组件TestFa.vue
<template>
<div>
<!--
1.子组件抛出自定义事件
-->
<!-- <TestSon :count="count" :arr="arr" :obj="obj" @update:changeCount="changeCount"></TestSon> -->
<!-- <TestSon :count="count" :arr="arr" :obj="obj" @update:changeCount="count=$event"></TestSon> -->
<!--
2. .sync修饰符
-->
<TestSon :count.sync="count" :arr="arr" :obj="obj"></TestSon>
</div>
</template>
<script>
import TestSon from './TestSon.vue';
export default {
data() {
return {
count: 1,
arr: [1, 2, 3],
obj: {
name: 'cjc',
age: 99
}
}
},
components: {
TestSon
},
methods: {
changeCount(val) {
this.count = val
}
}
}
</script>
子组件TestSon.vue
<template>
<div>
<h1>基本数据类型</h1>
{{ count }}
<button @click="changeCount">修改基本数据类型count</button>
<!-- <button @click="changeCount">修改基本数据类型count</button> -->
<h1>数组</h1>
{{ arr }}
<button @click="changeArr">修改数组</button>
<h1>对象</h1>
{{ obj }}
<button @click="changeObj">修改对象</button>
</div>
</template>
<script>
export default {
props: {
count: {
reuqire: true,
type: Number,
default: 0
},
arr: {
reuqire: true,
type: Array,
default: () => []
},
obj: {
reuqire: true,
type: Object,
default: () => { }
},
},
methods: {
// 1.子组件直接修改props接收的基本数据类型
// changeCount() {
// this.count = 100
// },
// 2.子组件抛出自定义事件修改props接收的基本数据类型
// changeCount() {
// this.$emit('update:changeCount',100)
// },
// 3.
changeCount() {
this.$emit('update:count', 200)
},
changeArr() {
this.arr.push(4)
},
changeObj() {
this.obj.name = 'CCC'
},
}
}
</script>