在VUE 3中重置组件反应性数据的最佳方法是什么?

发布于 2025-02-07 09:02:33 字数 874 浏览 1 评论 0原文

假设有一个具有多个反应性数据的组件。我们如何将它们重置回初始状态?

<script setup>
    const var_a = ref("");
    const var_b = ref([]);
    const var_c = ref({});
    const var_d = ref(false);
    const var_e = ref(1);
    const var_f = ref("a");
    ...
</script>

在VUE 2中,我们可以通过仅将Object.Assign()与对象使用object.sign()来做到这一点,然后只需在需要时将其重新定义为data()。

<script>
function initialData (){
  return {
    var_a: "",
    var_b: [],
    var_c: {},
    var_d: false,
    var_e: 1,
    var_f: "a",
  }
}

export default {
    data: function (){
        return initialState();
    },
    methods:{
        resetData: function (){
            Object.assign(this.$data, initialData());
        }
    }
}
</script>

但是在VUE 3中,它不起作用。

我可以将所有组件数据声明到const state然后循环槽,但感觉不只是一种方便的方式。

那么,将VUE 3上的这些方法重置的最佳方法是什么?

Let's say there is a component with multiple reactive data. How can we reset them back to the initial state?

<script setup>
    const var_a = ref("");
    const var_b = ref([]);
    const var_c = ref({});
    const var_d = ref(false);
    const var_e = ref(1);
    const var_f = ref("a");
    ...
</script>

In vue 2 we could do that by just using Object.assign() with an object and simply re/define it to data() whenever needed.

<script>
function initialData (){
  return {
    var_a: "",
    var_b: [],
    var_c: {},
    var_d: false,
    var_e: 1,
    var_f: "a",
  }
}

export default {
    data: function (){
        return initialState();
    },
    methods:{
        resetData: function (){
            Object.assign(this.$data, initialData());
        }
    }
}
</script>

But in vue 3 it does not work that way.

I could declare all the component data on to const state then loop trough it but it does not feel like a convenient way.

So what would be the best way to reset those on vue 3?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

榕城若虚 2025-02-14 09:02:33

如果需要重置整个状态,则不应单独定义。相反,它被定义为反应性对象:

const state = reactive(initialState());

可以以与以前相同的方式重置:

Object.assign(state, initialState());

如果需要,可以单独使用状态:

const { var_a } = toRefs(state);

If the whole state needs to be reset, it shouldn't be defined separately. Instead, it's defined as reactive object:

const state = reactive(initialState());

It can be reset the same way as before:

Object.assign(state, initialState());

The state can be used separately if needed:

const { var_a } = toRefs(state);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文