在官網(wǎng)均可找到解決方案
單向數(shù)據(jù)流
所有的 props 都遵循著單向綁定原則,props 因父組件的更新而變化,自然地將新的狀態(tài)向下流往子組件,而不會逆向傳遞。這避免了子組件意外修改父組件的狀態(tài)的情況,不然應用的數(shù)據(jù)流將很容易變得混亂而難以理解。
另外,每次父組件更新后,所有的子組件中的 props 都會被更新到最新值,這意味著你不應該在子組件中去更改一個 prop。若你這么做了,Vue 會在控制臺上向你拋出警告:
export default {
props: ['foo'],
created() {
// ? 警告!prop 是只讀的!
this.foo = 'bar'
}
}
導致你想要更改一個 prop 的需求通常來源于以下兩種場景:
-
prop 被用于傳入初始值;而子組件想在之后將其作為一個局部數(shù)據(jù)屬性。在這種情況下,最好是新定義一個局部數(shù)據(jù)屬性,從 props 上獲取初始值即可:
export default {
props: ['initialCounter'],
data() {
return {
// 計數(shù)器只是將 this.initialCounter 作為初始值
// 像下面這樣做就使 prop 和后續(xù)更新無關(guān)了
counter: this.initialCounter
}
}
}
?2.?需要對傳入的 prop 值做進一步的轉(zhuǎn)換。在這種情況中,最好是基于該 prop 值定義一個計算屬性:文章來源:http://www.zghlxwxcb.cn/news/detail-422180.html
export default {
props: ['size'],
computed: {
// 該 prop 變更時計算屬性也會自動更新
normalizedSize() {
return this.size.trim().toLowerCase()
}
}
}
另一種在組件內(nèi)實現(xiàn)?v-model
?的方式是使用一個可寫的,同時具有 getter 和 setter 的計算屬性。get
?方法需返回?modelValue
?prop,而?set
?方法需觸發(fā)相應的事件:文章來源地址http://www.zghlxwxcb.cn/news/detail-422180.html
<!-- CustomInput.vue -->
<script>
export default {
props: ['modelValue'],
emits: ['update:modelValue'],
computed: {
value: {
get() {
return this.modelValue
},
set(value) {
this.$emit('update:modelValue', value)
}
}
}
}
</script>
<template>
<input v-model="value" />
</template>
到了這里,關(guān)于Vue3 v-model cannot be used on a prop,的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!