vue3 如何优雅的初始化 state 的数据?

现在原始数据如下:

const state = reactive({
      cm1: "", // 长度1
      cm2: "", // 长度2
      cm3: "", // 长度3
      volume: "", // 体积
    });

如果使用最简单的方式初始化:

state.cm1 = ""
state.cm2 = ""
state.cm3 = ""

但是这样如果数据很多的情况下, 重置起来特别不友好.

有没有一种特别优雅的方式重置 state 数据呢?

cnguu
最佳答案
const createState = () => ({
  cmd1: '',
  cmd2: '',
  cmd3: '',
  volume: '',
});

const state = reactive(createState());

const resetState = () => {
  Object.assign(state, createState());
};
1年前 评论
ziming007 (楼主) 1年前
讨论数量: 2
cnguu
const createState = () => ({
  cmd1: '',
  cmd2: '',
  cmd3: '',
  volume: '',
});

const state = reactive(createState());

const resetState = () => {
  Object.assign(state, createState());
};
1年前 评论
ziming007 (楼主) 1年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!