[英]Ember this.set in component
我似乎對Ember組件的init
屬性做錯了。
我的代碼看起來像這樣。
import Ember from 'ember';
export default Ember.Component.extend({
init(){
this._super(...arguments);
this.set('initial_value', this.get('value'));
},
change(e){
console.log('value should be reset to ' + this.get('initial_value')) //This prints the initial value correctly.
this.set('value', this.get('initial_value')); // this line does not update value.
//this.set('value', 'hello'); //this line does update value.
}
});
為什么我可以使用字符串文字更新value
,而不能使用this.get('initial_value')
更新value
?
我嘗試了這段代碼,將組件生命周期中的每個函數init
為init
。 我這樣做是因為我認為它與渲染有關。 還是那樣。
這是玩笑 。
既然您已經使用<input type="text" value={{value}}>
,則它是單向綁定。 即,在更改組件中的value
,更改將反映在輸入框中,但是更改輸入框中的值將不會更改組件中變量value
。
在Ember中,僅當組件中變量的值更改時DOM才會更新。 在my-component.js
,變量value
沒有改變。 它僅包含字符串文字initial value
。
例如, this.set('value', Math.random());
這將在變量value
更改時起作用。
為什么我可以使用字符串文字更新值,而不能使用this.get('initial_value')更新值?
該值只能更改一次,因此只能執行一次。 (在第一次將值更改為字符串時)
要解決這個問題 ,您可以使用{{input value=value}}
來實現雙向綁定。 編輯輸入框時,變量value
更改。
重點關注時, this.set('value',this.get('initial_value'))
, this.set('value',this.get('initial_value'))
將根據需要設置初始值。
你可以只包括{{input value=value}}
在我-component.hbs文件,當你改變輸入,它會調用change
功能在輸入助手,它將調用change
你的組件的功能,將其復位即可initial_value
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.