How to set a component non-reactive data in Vue 2?

2019-04-04 06:49发布

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>

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

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

My create hook:

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

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?

3条回答
孤傲高冷的网名
2楼-- · 2019-04-04 07:01

I prefer using static data (non reactive) like this:

  1. Create a mixin (i name it static_data.js) with the follow content

    static_data.js

  2. In your components where you want to use static data you can do:

ExampleComponent.vue

Note: The genious of this code is samuelantonioli in the comments here.

查看更多
Bombasti
3楼-- · 2019-04-04 07:09

Actually, setting properties on this in created() should work out of the box:

<template>
  <div id="app">
    <ul>
      <li v-for="item in myArray" :key="item">
        {{ item }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "app",
  created() {
    this.myArray = [
      'item 1',
      'item 2'
    ];
  }
};
</script>

will render

<div id="app">
  <ul>
    <li>
      item 1
    </li>
    <li>
      item 2
    </li>
  </ul>
</div>

Demo here: https://codesandbox.io/s/r0yqj2orpn .

查看更多
狗以群分
4楼-- · 2019-04-04 07:14

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

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>

Here is the fiddle

查看更多
登录 后发表回答