求问vue3通过reactive创建的数据怎么进行初始化

admin
  • 34

在vue2中可以通过this.$options.data().xxx直接赋值 那在vue3的setup中咋整。。。

回复
阅读 3k
3 个回答

这样?

{
  setup () {
    const getInitalState = () => {
      return {
        a: 1
      }
    }
    
    const state = reactive(getInitalState())
    
    const resetState = () => {
      Object.assign(state, getInitalState())
    }
  }
}

不明白你的初始化是什么意思。。一般直接声明使用就好了

<List :data="data.list">
...
...
setup() {
  let data = reactive({
     list:[]
  })
  let loadData = () => {
     data.list = [{name:'a'},{name:'b'}]
  }
  loadData()
  return {
    data
  }
}
# https://github.com/bravf/vue2hooks/blob/master/src/hooks/quickState.js
# 参考这个老哥的方法,我这里直接改成reactive了。因为composition-api里面的reactive也是基于observable实现的。不用在单独取一遍。。
<template>
  <div>
    <label label="name">
      <input v-model="writeQState.state.name" />
    </label>
    <label label="gender">
      <input v-model="writeQState.state.gender" />
    </label>
    <button @click="writeQState.reset">Reset</button>
  </div>
</template>
<script>
import { defineComponent, reactive } from "@vue/composition-api";
import clonedeep from "lodash.clonedeep";
export default defineComponent({
  setup() {
    const useQuickState = (params = {}) => {
      const state = reactive(params);
      const backupState = clonedeep(state);
      const reset = () => {
        Object.assign(state, cloneBackup());
      };
      const clone = () => clonedeep(state);
      const cloneBackup = () => clonedeep(backupState);
      return {
        state,
        backupState,
        clone,
        reset,
        assign: (newParams) => Object.assign(state, newParams),
        cloneBackup,
      };
    };

    const writeQState = useQuickState({
      name: "123",
      gender: "444",
    });
    return {
      writeQState,
    };
  },
});
</script>
你知道吗?

宣传栏