vue中子組件不能直接修改父組件傳來的prop值,Prop 是一種傳遞數據的機制,父組件通過 Prop 向子組件傳遞數據,子組件通過 Props 接收父組件傳遞過來的數據,這些數據被封裝成一個個解構體形式的對象,不能直接進行修改。這樣做的好處是保證了單向數據流,即只有父組件能夠更新 Prop,然后數據會自動流向子組件,從而避免了數據的混亂與不可預測性。
方法一:
使用事件觸發機制
?在 Vue 中,子組件可以通過 $emit() 方法來觸發父組件中定義的事件。當父組件收到事件時,它可以調用一個方法來更新它自己的狀態,傳遞給子組件一個新的 Prop。這種方式可以讓子組件告訴父組件需要更新的數據,而不是直接修改它。
<!--父組件-->
<template><div><chlid :prop1="msg" @change-msg="changeMsg"></chlid></div>
</template>
<script>
import Child from "./Child.vue";
export default{components:{Child},data(){return{msg:"Hello,Vue!"}},methods:{changeMsg(newMsg){this.msg=newMsg;//更新父組件中的數據}}
}
</script>
<!--子組件Child.vue-->
<template><div>{{prop1}}<button @click="changeMsg">Change Message</botton></div>
</template>
<script>
export default{props:{prop1:String},methods:{changeMsg(){this.$emit("change-msg","Hello,world!")//觸發事件并傳遞新值}}
}
</script>
?方法二:
使用計算屬性
計算屬性本質上是一個函數,它接收一個參數,并且返回一個根據這個參數計算得到的值。這個值可以在組件的模板中使用。
<!--父組件-->
<template><div><chlid :prop1="msg"></chlid></div>
</template>
<script>
import Child from "./Child.vue";
export default{components:{Child},data(){return{msg:"Hello,Vue!"}}
}
</script>
<!--子組件Child.vue-->
<template><div>{{modifiedProp}}<button @click="changeMsg">Change Message</botton></div>
</template>
<script>
import Child from "./Child.vue";
export default{props:{prop1:String}computed:{modifiedProp:{get(){return this.prop1},set(newVal){this.$emit("update:prop1",newVal)}}}methods:{changeMsg(){this.modifiedProp="Hello,world!";//使用計算屬性更新Prop的值}}
}
</script>