简体   繁体   English

在 vuex getter 中访问 Nuxt 插件 function

[英]Accessing Nuxt plugin function in vuex getter

I am getting started with nuxtjs and vuex.我开始使用 nuxtjs 和 vuex。 I just encountered an issue accessing a combined injected plugin function from a getter.我刚刚遇到了一个从 getter 访问组合注入插件 function 的问题。 Eg:例如:

nuxt.config.js nuxt.config.js

...
plugins: [
  '~/plugins/myplugin.js'  
  ],
...

~/plugins/myplugin.js ~/plugins/myplugin.js

function doSomething(string) {
        console.log("done something: " + string)
    }

export default ({ app }, inject) => {
    inject('doSomething', (string) => doSomething(string))
  }

~/store/index.js ~/store/index.js

export const actions = {
    someAction({commit}) {
        this.$doSomething("Called from Action") // works
    }
}

export const getters = {
    someGetter: state => {
        this.$doSomething("Called from Getter") // throws error
    }
}

The code works for the action someAction but the call in getter someGetter will result in a error suggesting this is undefined.该代码适用于操作someAction但 getter someGetter中的调用将导致错误提示this是未定义的。

The nuxt documentation only shows examples for accessing injected plugin functions from mutations and actions but does not explicitly mention that getters can not access plugin functions. nuxt 文档仅显示了从突变和操作访问注入插件函数的示例,但没有明确提到 getter 不能访问插件函数。 Is this even possible in nuxt or is there a good reason not to call a plugin method in a getter?这在 nuxt 中是否可能,或者是否有充分的理由不在 getter 中调用插件方法? Any help appreciated.任何帮助表示赞赏。

You shouldn't try to do_something in a getter.你不应该尝试在do_something中做一些事情。 Getters are for deriving state from your store's state only. Getter 仅用于从商店的 state 派生 state。 The point being that you don't have to separately store and keep up-to-date the derived state.关键是您不必单独存储和更新派生的 state。 For example you have a list of tasks and you have a getter for completed tasks instead of a separate list of done tasks: completedTasks: state => state.tasks.filter(task => task.completed) .例如,您有一个任务列表,并且您有一个已完成任务的 getter,而不是一个单独的已完成任务列表: completedTasks: state => state.tasks.filter(task => task.completed)

Mutations should only be used for mutating your store's state.突变只能用于突变您商店的 state。

Finally, in actions you can interact with whatever you need, like a webserver API somewhere or this.$do_something and then fire off mutations to update the state based on the results.最后,在操作中,您可以与所需的任何内容进行交互,例如某处的网络服务器 API 或this.$do_something ,然后触发突变以根据结果更新 state。

So I'd say it makes sense what Nuxt is doing here, to inject in the actions but not to the getters.所以我想说 Nuxt 在这里所做的事情是有道理的,注入动作而不是吸气剂。

I faced the same issue and I was able to get around it by doing我遇到了同样的问题,我能够通过这样做来解决它

export const getters = {
  someGetter: state => {
    $nuxt.$doSomething("Called from Getter") // Grab $nuxt from the global scope
  }
}

Not sure if this works in SSR mode however但是不确定这是否适用于 SSR 模式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM