【问题标题】:Accessing nuxt $store inside Dynamic Component在动态组件中访问 nuxt $store
【发布时间】:2019-08-10 22:32:27
【问题描述】:

我正在开发一个基于 Promise 的模态组件,它提供了将组件指定为模态本身的主体的可能性。为了达到这个结果,我认为一个好的解决方案是在模态模板中使用动态组件。 但是,在 NUXT 应用程序中,如果组件引用了 Vuex 实例(this.$store),则结果是未定义的(或者更好的是没有 $store 对象属性)。同样,在插件内部进行的任何注入都会导致未定义(例如,inject('api', api) 创建属性 $api,但结果未定义)。 如果我只是以“标准”方式使用组件(例如,将其放在页面或其他组件模板中),一切正常。

在以编程方式传递组件之前,我应该做一些“额外的注入”。

谁能帮帮我?

NUXT 项目结构(简化):

  • /pages/index.vue
  • /plugins/api.js
  • /store/auth.js
  • /components/HelloComponent.vue

/plugins/api.js

let api = {}

api.call = function (request, auth, unpack, axios = this.axios) {
  if (!request) Error('backend.js:call invalid params:', request, auth, unpack, axios)

  if (auth) {
    if (request.headers)
      request.headers['Authorization'] = 'Bearer ' + this.auth.accessToken
    else
      request.headers = { 'Authorization': 'Bearer ' + this.auth.accessToken }
  }
  return axios(request).then((response) => unpack ? response.data : response)
}

api.getAPI = function (api, params, auth = true, unpack = true) {
  if (!api) Error('api.js:getAPI invalid params:', api)
  console.log('api.js:getAPI api:', api)
  return this.call({ method: 'get', url: api, params: params }, auth, unpack)
}

api.postAPI = function (api, params, data, auth = true, unpack = true) {
  if (!api) Error('api.js:postAPI invalid params:', api, data)
  console.log('api.js:postAPI api:', api)
  return this.call({ method: 'post', url: api, params: params, data: data }, auth, unpack)
}


/*******************************************************/
/*         NUXT plugin and reference injection         */
/*******************************************************/

export default function (context, inject) {

  console.log('[CALL] api.js')

  /* assign global $axios instance */
  api.axios = context.$axios

  /* assign auth instance to access tokens */
  api.auth = context.store.state.auth

  /* inject backend reference into application instance */
  inject('api', api)
}

/pages/index.vue

<template>
  <div>
  
    <span>
      {{ $store.auth.state.name }} // -> Displays 'Chuck'
    </span>
    
    /* Object.keys(this).includes('$store): false'; Object.keys(this).includes('$auth): true' */
    <component :is="cComponent" /> // -> this.$store is undefined; auth: undefined
    
    <hello-component /> // -> Displays 'Chuck'; auth: Object {...}
  </div>
</template>

<script>
import HelloComponent from '../components/HelloComponent.vue'
export default {

  components: {
    HelloComponent
  },
  
  created () {
    this.$store.commit('auth/setName', 'Chuck')
  },
   
  computed: {
    cComponent () {
      return HelloComponent
    }
  }
}
</script>

/components/HelloComponent.vue

<template>
  <span>
    {{ $store.auth.state.name }}
  </span>
</template>

<script>
export default {

  created() {
    console.log('auth:', this.$auth)
  }
  
}
</script>

/store/auth.js

export const state = () => ({
  accessToken: null,
  refreshToken: null,
  name: null,
})

export const mutations = {

  setAccessToken(state, token) {
    console.info('auth.js:setAccessToken', token)
    state.accessToken = token
  },

  setRefreshToken(state, token) {
    console.info('auth.js:setRefreshToken', token)
    state.refreshToken = token
  },

  setName(state, name) {
    console.info('auth.js:setName', name)
    state.user = name
  },

}

【问题讨论】:

  • 显示代码,否则无法分辨
  • 我发布了一个复制问题的简单代码。但是,如您所见,当您在以编程方式创建的组件中引用 NUXT 全局变量时,就会出现问题。我的想法是NUXT注入功能不会影响这种组件。
  • 你能在代码沙盒上创建一个最小的复制吗?我无法重现它。这里是带有动态组件的示例并存储在其中codesandbox.io/s/20x6m79jzp
  • 您提供的代码和框给了我一个小错误,它不会在已安装的方法中打印日志。我修改了您示例的一部分以满足我的需要,令人惊讶的是它似乎有效。但是,在我的本地项目中放置这样的代码时,问题又回来了。所以我会进行调查,以便在codeandbox上重现此类问题并与您分享。
  • 有问题的 Github repo 也可以复制

标签: javascript vue.js vuejs2 vue-component nuxt.js


【解决方案1】:

如果你在Nuxt项目中没有this指针的访问权限,而你确实需要访问store,那么直接使用

window.$nuxt.$store 而不是 this.$store;

希望它能解决你的问题

【讨论】:

  • 感谢您的回答。问题是我想以静态和动态方式使用组件。所以我认为在静态声明的组件中使用 window.$nuxt.$store 有点棘手,因为可以直接使用 this.$store。另一方面,不可能知道用户是否会在动态时装中使用组件,这意味着她/他必须意识到这样的问题(这不是可移植的解决方案)。
  • 什么?那是不正确的。您可以在 nuxt 中访问它。您唯一无法访问的地方是 asyncData/fetch
猜你喜欢
  • 2020-04-11
  • 2019-08-16
  • 1970-01-01
  • 2021-04-14
  • 2021-02-23
  • 2018-10-21
  • 2019-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多