本文是工作中遇到问题解决后的记录,方便以后查阅。
父组件传值给子组件props,子组件将props接受到的值用做v-model双向数据绑定
因为props是只读的,不能修改 直接修改会报下面的错误
Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "isShow"
避免直接改变 prop,因为每当父组件重新渲染时,值都会被覆盖。 相反,根据道具的值使用数据或计算属性。 道具被变异:“isShow”
网上也看到了解决方案:子组件的props传值给data。为一般认为,props的值是只读的,只有data才可以修改,所以要将props传给data。但是在我这里并没有什么卵用。
后来做了一番“骚操作”,用 computed 的set、get方式来做中转。
// 父组件
<template>
<div @click="handleChangeShow"></div>
<AnchorRecruitPopup :isShow.sync="show"></AnchorRecruitPopup>
</template>
export default {
name: "anchorRecruit",
data() {
return {
show: false
};
},
components: {
AnchorRecruitPopup
},
methods: {
handleChangeShow() {
this.show = true;
},
}
// 子组件
<template>
<van-popup
v-model="show"
:round="true"
closeable
close-icon="close"
close-icon-position="bottom-right"
>
<div>内容</div>
</van-popup>
</template>
<script>
export default {
props: ["isShow"], //接收父组件传值
computed: {
show: {
get() {
return this.isShow;
},
set(val) {
this.$emit("update:isShow", val);
},
},
},
};
</script>