下面的 vuejs 組件代碼成功地為 playerName、time 和 errors 設定了資料的初始狀態。將初始資料提取到函式允許我輕松地將資料重置回初始狀態。
太好了...但是...我只希望時間和錯誤重置為初始狀態,并且我希望 playerName 繼續存在。
有沒有推薦的方法來實作這一點?我似乎只能找到全有或全無的方法或笨拙的手動重置方法,這需要我記住將來是否更改。
感謝您的尋找和任何幫助。
function initialState (){
return {
playerName: '',
time: 0,
errors: 0
}
}
//In my component:
data: function (){
return initialState();
}
//Call this method when I want to start over
methods:{
reset: function (){
Object.assign(this.$data, initialState());
}
}
uj5u.com熱心網友回復:
在重新分配之前,您可以采用初始狀態并重新合并您的維護者,然后使用超級速記行內合并:
export default {
data: () => ({
playerName: '',
time: 0,
errors: 0
})
methods: {
reset () {
const playerName = ...this.playerName; // Use Spread (...) to clone this.playerName so we don't assign a reactive copy that becomes blank again.
return Object.assign(this.$data, { ...this.$options.data(), playerName })
}
}
}
行內合{ ...this.$options.data(), playerName }并是 ES6 的特性,playerName注入與撰寫相同:
{ ...this.$options.data(), playerName: this.playerName }
在this.$options.data()做什么:
{ ...{ playerName: '', time: 0, errors: 0 }, playerName: this.playerName },
這三個點稱為Spread Syntax,基本上它是將data物件合并到我們新的{}空物件中,然后我們在注入后覆寫屬性。
這總體上相當于寫作:
Object.assign(this.$data, () => {
const data = { playerName: '', time: 0, errors: 0 }
data.playerName = this.playerName
return data
}())
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/378487.html
上一篇:將類似的計算屬性轉換為僅使用一個
