如何在 Vue 2 中设置组件非反应性数据? [英] How to set a component non-reactive data in Vue 2?

查看:41
本文介绍了如何在 Vue 2 中设置组件非反应性数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个分类数组,它被加载一次(在创建的钩子中),然后它一直是静态的.我在组件模板中呈现这个数组值.

I have a categories array, which is loaded once (in created hook) and then it is static all the time. I render this array values in a component template.

<template>
    <ul>
        <li v-for="item in myArray">{{ item }}</li>
    </ul>
</template>

我的数据属性看起来(它不包括 myArray - 我不想要反应式绑定):

My data property looks (it does not include myArray - I dont want reactive binding):

data() {
    return {
        someReactiveData: [1, 2, 3]
    };
}

我的创建钩子:

created() {
    // ...
    this.myArray = ["value 1", "value 2"];
    // ...
}

问题是,Vue 抛出错误 - 我不能在模板中使用 myArray,因为在创建 DOM 时未创建此变量 - 已挂载.

Problem is, that Vue throw error - I cant use myArray in a template, because this variable is not created when the DOM is created - mounted.

那么怎么做呢?或者哪里可以存储组件常量?

So how to do this? Or where can be stored component constants?

推荐答案

Vue 将 data 选项中的所有属性设置为 setter/getter 以使其具有反应性.请参阅深入了解反应性

Vue sets all the properties in the data option to setters/getters to make them reactive. See Reactivity in depth

由于您希望 myArray 是静态的,您可以将其创建为自定义选项,可以使用 vm.$options

Since you want myArray to be static you can create it as a custom option which can be accessed using vm.$options

export default{
    data() {
        return{
            someReactiveData: [1, 2, 3]
        }
    },
    //custom option name myArray
    myArray: null,
    created() {
        //access the custom option using $options
        this.$options.myArray = ["value 1", "value 2"];
    }
}

您可以在模板中迭代此自定义选项,如下所示:

you can iterate over this custom options in your template as follows:

<template>
    <ul>
        <li v-for="item in $options.myArray">{{ item }}</li>
    </ul>
</template>

这是小提琴

这篇关于如何在 Vue 2 中设置组件非反应性数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆