[英]vue js passing “top-level” Boolean not working, only nested
這很奇怪。 當我在頂層定義布爾屬性showModal
時,它只是被vue.js忽略。 這就是我在做的事情:
//Component:
export default {
props:['rating', 'showModal'],
data: function data () {
return {
rating: this.rating,
showModal: this.showModal
};
}
};
調用視圖:
const sharedRating = {
title: '',
remark: ''
};
let showModal = false;
new Vue({
el: '#rating-edit-container',
data: {
showModal: showModal,
rating: sharedRating
}
});
showModal = true;
然后將兩個值傳遞給組件:
<rating-edit
:rating="rating"
:show-modal="showModal"></rating-edit>
但是當我改變showModal
的值時沒有任何反應。
如果我在rating對象中傳遞showModal
並使用該嵌套屬性一切正常:
const sharedRating = {
showModal: false,
title: '',
remark: ''
};
new Vue({
el: '#rating-edit-container',
data: {
rating: sharedRating
}
});
sharedRating.showModal = true;
不應該“獨立”布爾屬性也可以在Vue中工作,還是總是需要“包裹”?
好吧,首先,我不確定您的組件中發生了什么,因為您命名的屬性和具有相同名稱的數據值。 沒有測試,我不確定哪一個獲勝,但它看起來像是數據屬性。 你不應該名稱的屬性和數據值同樣的事情。 該物業將永遠為您服務。
在組件中定義數據函數時,記住只在創建組件時才調用數據函數也很重要。 在哪里設置
showModal: this.showModal
(暫時忽略我上面所說的關於這不是一個好主意)showModal 數據屬性只設置一次 。 除非您在組件內部更新,否則永遠不會更新它。 它不會收到屬性showModal
更改。
如果你想要的組件來獲得更新showModal
來自外部和變化showModal
在組件的組件之外 relfected,你需要不同的方式處理這一點。
Vue組件由props down,events up結構組成。
export default {
props:['rating', 'showModal'],
data: function data () {
return {
rating: this.rating,
};
},
computed:{
show:{
get(){ return this.showModal; }
set(v){ this.$emit('input', v) }
}
}
};
然后修改您在模板中使用它的方式:
rating-edit
:rating="rating"
v-model="showModal"></rating-edit>
以這種方式編寫您的組件,任何更新showModal
在組件外將組件作為內部反射show
,任何改變show
里面的組件將被發射到父。 然后因為v-model
監聽input
事件,所以父級中的showModal
將使用新值進行更新。
現在你可能會問這個問題,但是當showModal
是一個對象的屬性時,它為什么會起作用?
當您將對象從頂層向下傳遞到組件中時,在Vue之外,根Vue和組件都在使用同一個對象。 任何這些地方對showModal
屬性的任何更改都將反映在所有這些地方。 但是, 如果您通過創建一個新的sharedRating
對象來更新showModal
,您會看到與使用布爾值時所看到的行為類似的行為。 Vue中的屬性是不可變的 ,這意味着您對原始 javascript值(字符串,數字,布爾值等)所做的任何更改都不會反映在組件外部 ,事實上 ,如果您使用的話,Vue會發出警告開發版。 但是,javascript中的對象和數組是通過引用傳遞的。 引用是不可變的,但可以更改對象的屬性和數組的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.