在vuejs中重置为初始数据,但仅针对某些值

Reset to initial data in vuejs, but only for some of the values

下面的 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());
    }
}

您可以采用初始状态并在使用超级 shorthand 内联合并重新分配之前将您的 keepers 与其重新合并:


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

}())