如何使 Nuxt 成为全局对象?

양정훈*_*양정훈 6 javascript vue.js nuxt.js

我想创建可以在每个地方全局可用的自定义对象(插件、中间件、组件的创建/计算/挂载方法)

我可以使用上下文属性(自定义插件、自定义路由器中间件...)访问全局对象,

但是如何在组件中访问它created()?

Man*_*piK 18

也可以注入一个对象。如果您想创建随处可用的插件,则很有用。

这里是关于这个组合注入的nuxt 文档。

// nuxt.config.js

export default {
  plugins: ['~/plugins/myPlugin.js']
}
Run Code Online (Sandbox Code Playgroud)
// plugins/myPlugin.js

import Vue from 'vue'

export default ({ app }, inject) => {
  inject('myPlugin', Vue.observable({ foo: 'bar' }))
}
Run Code Online (Sandbox Code Playgroud)

然后你可以通过 prefix 访问你的插件$。

// components/MyComponent.vue

<template>
    <div :class="$myPlugin.foo">
        {{ $myPlugin.foo }}
    </div>
</template>

<script>
export default {
  methods: {
    aMethod() {
      return this.$myPlugin.foo
    }
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

它也可以在 vuex 和 nuxt 服务器上下文中使用。
您可以注入对象或函数。

在这里了解有关客户端/服务器注入的更多信息。


Nic*_*nec 7

您可以使用 store 来获取全局变量:

https://nuxtjs.org/guide/vuex-store


1/创建商店:

// your-project/store/index.js

export const state = () => ({
  var1: null,
  var2: null
})

export const mutations = {
  SET_VAR_1 (state, value) {
    console.log('SET_VAR_1', value)
    state.var1 = value
  },
  SET_VAR_2 (state, value) {
    console.log('SET_VAR_2', value)
    state.var2 = value
  }
}
Run Code Online (Sandbox Code Playgroud)

2/ 读取数据存储

然后您可以从任何or或or获取或设置var1& 。var2<page>.vue<layout>.vue<plugin>.vue<middleware>.vue

从<template>有$store:

// your-project/pages/index.js

<template>
  <section>
    <h2>From Store</h2>
    <div>var1 = {{ $store.state.var1 }}</div>
    <div>var2 = {{ $store.state.var2 }}</div>
  </section>
</template>
Run Code Online (Sandbox Code Playgroud)

或从<script>注射开始asyncData:

// your-project/pages/index.js

<template>
  <section>
    <h2>From Store</h2>
    <div>var1 = {{ var1 }}</div>
    <div>var2 = {{ var2 }}</div>
  </section>
</template>

<script>
export default {
  async asyncData ({ store }) {
    return {
      var1: store.state.var1,
      var2: store.state.var2
    }
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

3/ 更新数据存储

<script>
export default {
  async asyncData ({ store }) {

    store.commit('SET_VAR_1', 'foo')
    store.commit('SET_VAR_2', 'bar')
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

4/ 组件和商店

从<component>.vue您不必直接获取商店。

因此,您必须使用自定义属性将数据从 nuxt 文件传递​​到组件文件:

// your-project/pages/example.js

<template>
  <section>
    <my-component :var1="$store.state.var1" :var2="$store.state.var2" />
  </section>
</template>
Run Code Online (Sandbox Code Playgroud)

然后

// your-project/components/MyComponent.js
<template>
  <section>
    <h2>From props</h2>
    <div>var1 = {{ var1 }}</div>
    <div>var2 = {{ var2 }}</div>
  </section>
</template>

<script>
  export default {
    props: ['var1', 'var2']
  }
</script>
Run Code Online (Sandbox Code Playgroud)