在做项目时有时候会遇到这种错误
这句话的意思是说,避免直接改变道具,因为只要父组件重新渲染,该值就会被覆盖。相反,使用基于道具值的数据或计算属性。
就是不能直接改变父组件传过来的props,所以怎么办呢,可以使用emit来触发父组件的事件。
父组件
<template>
<div class="class">
<Student :show="isShow" @hideStudent="hideStudent" />
<button @click="showStudent">点我显示学生</button>
</div>
</template>
<script>
import Student from "./student";
export default {
name: "class",
components: { Student },
data() {
return {
isShow: false,
};
},
methods: {
showStudent() {
this.isShow = true;
},
hideStudent() {
this.isShow = false;
},
},
};
</script>
子组件
<template>
<div class="student" v-show="show">
<nav>Mike</nav>
<button @click="close">点我关闭student</button>
</div>
</template>
<script>
export default {
name: "student",
props: {
show: {
type: Boolean,
default:false
},
},
methods: {
close() {
this.$emit("hideStudent");
},
},
};
</script>
当然子组件也可以这么写,用watch来监听
<template>
<div class="student" v-show="showStudent">
<nav>Mike</nav>
<button @click="close">点我关闭student</button>
</div>
</template>
<script>
export default {
name: "student",
props: {
show: {
type: Boolean,
default:false
},
},
data() {
return {
showStudent:false
};
},
watch:{
show(){
this.showStudent=this.show
},
},
methods: {
close() {
this.$emit("hideStudent");
},
},
};
</script>
最后来看效果图


具体关于VUEprops传值问题可以看vue父子组件传值
最后!!!注意!!!
基本类型:字符串(String)、数字(Number)、布尔(Boolean)、空(Null)、未定义(Undefined)、Symbol。
引用数据类型:对象(Object)、数组(Array)、函数(Function)。
props可以直接修改 引用数据类型
原因:对象类型是存放在堆空间的,在栈空间中只是保留了对象的引用地址,当 JavaScript 需要访问该数据的时候,是通过栈中的引用地址来访问的,所以,父组件传递给子组件的,实际上只是一个引用地址,当子组件修改这个对象时,是真的修改了在堆空间中保存的数值,当然父组件中的值也会发生变化,但是引用地址没有进行修改,所以可以直接修改。
在 Vue 中,应当避免直接修改父组件传来的 props,因为这可能导致数据覆盖。正确做法是使用 $emit 触发父组件的方法进行状态更新,或者在子组件内部创建基于 props 的数据副本。例子展示了如何使用 $emit 实现子组件关闭事件的传递,以及通过 watch 监听 prop 并更新子组件内部状态。理解 props 的单向数据流对于优化组件间通信至关重要。
5万+

被折叠的 条评论
为什么被折叠?



