实例上可用的 Vue 非反应性数据

Vue non reactive data available on instance

我想在 vue 中存储对象,它应该对整个实例可用,而不是反应性的。通常(有反应)我会像这样使用 'data':

new Vue({
  data: myObject
})

但实际上 myObject 不需要更改,所以我认为让它响应是不好的。有什么方法可以做到这一点吗?

您可以使用 Vue 实例属性。

There may be data/utilities you’d like to use in many components, but you don’t want to pollute the global scope. In these cases, you can make them available to each Vue instance by defining them on the prototype:

Vue.prototype.$appName = 'My App'

现在 $appName 在所有 Vue 实例上都可用,甚至在创建之前。如果我们 运行:

new Vue({
  beforeCreate: function () {
    console.log(this.$appName)
  }
})

参考:Link

您可以为该数据使用 Vuex 状态 属性 并仅在您想要更改值时定义突变。

如果您已经在使用 Vuex,只需将您的数据设置到商店的 状态 并且不要提供任何更改以使其保持只读状态。

例如...

const store = new Vuex.Store({
  state: myObject
})

// assuming you've added Vue.use(Vuex) if using a module system
new Vue({
  // el, data, etc
  store
})

然后你的 Vue 实例或组件可以访问

this.$store.state.somePropertyOfMyObject