【问题标题】:How to make a Vue 3 object property reactive如何使 Vue 3 对象属性具有反应性
【发布时间】:2021-06-04 20:26:23
【问题描述】:

如何创建对象属性reactive

当我运行下面的代码时,导入的visible 不会更改为true

导入对象的组件:

<template>
    <div class="context">
        <span v-if="visible"> test </span>
    </div>
</template>
<script>
import { ContextManager } from "./utils.js";
import { ref } from "vue";

export default {
    name: "context",
    setup() {
        const visible = ref(ContextManager.visible);

        return { visible };
    }
};
</script>

向对象添加数据的其他组件:

const openContext = (e) => {
    e.preventDefault();
    ContextManager.add({
        el: e.target,
        items: contextItems
    },e );
};

ContextManager 对象:

import { reactive } from "vue";

export const ContextManager = reactive({
    context: null,
    visible: false,
    add(context, e) {
        this.visible = true;
    }
});

【问题讨论】:

    标签: javascript vue.js vue-component vuejs3 vue-reactivity


    【解决方案1】:

    对象的属性不是 refs,因此当您提取 visible 属性时,与原始对象没有任何连接,因为它只是一个普通的布尔值。

    为此提供了toRef api 方法,以维护此连接:

    可用于为源反应对象上的属性创建引用。然后可以传递 ref,保留与其源属性的反应连接。

    导入toRef 方法并像这样使用它:

    import { toRef } from 'vue'
    
    const visible = toRef(ContextManager, 'visible');
    

    【讨论】:

      猜你喜欢
      • 2021-06-05
      • 2020-01-06
      • 1970-01-01
      • 1970-01-01
      • 2017-11-03
      • 1970-01-01
      • 2019-11-20
      • 2019-07-16
      • 2018-06-13
      相关资源
      最近更新 更多