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

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

问题描述

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

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 设置者/获取者的选项,以使其反应。参见深度反应

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天全站免登陆