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

前端 未结 5 1071
别跟我提以往
别跟我提以往 2020-12-03 10:05

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.

<         


        
5条回答
  •  自闭症患者
    2020-12-03 10:24

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

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

    import Vue from 'vue'
    
    Vue.prototype.$static = {}
    
    export default {
      beforeCreate () {
        const vue_static = this.$options.static
        const vue_static_destination = this.$static || this
    
        if (vue_static && typeof(vue_static) === 'function') {
          Object.assign(vue_static_destination, vue_static.apply(this))
        } else if (vue_static && typeof(vue_static) === 'object') {
          Object.assign(vue_static_destination, vue_static)
        }      
      }
    }
    

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

    import use_static_data from '@mixins/static_data'
    
    export default {
      mixins: [use_static_data],
    
      static: () => ({
        static_value: 'Vue is awesome'
      }),
    
      created () {
        console.log(this.$static.static_value); // Vue is awesome
      }
    }
    

    There is also a package vue-static

    Credits here.

提交回复
热议问题