在vuex getter中访问Nuxt插件函数。

问题描述 投票:0回答:1

我正在开始使用nuxtjs和vuex。我只是遇到了一个问题,从getter访问一个组合注入的插件函数。例如

nuxt.config.js

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

~pluginsmyplugin.js

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

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

~storeindex.js

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

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

这段代码可以用于动作 someAction 但在getter中的调用 someGetter 将导致一个错误,表明 this 是未定义的。

nuxt文档中只展示了从突变和动作中访问注入的插件函数的例子,但没有明确提到getter不能访问插件函数。这在nuxt中是可能的吗,或者有什么好的理由不在getter中调用插件方法?感谢任何帮助。

javascript plugins vuex nuxt.js
1个回答
0
投票

你不应该尝试 do_something 中的状态。Getter只用于从你的store的状态中派生状态。重点是你不必单独存储和更新派生的状态。例如,你有一个任务列表,你有一个用于完成任务的getter,而不是一个单独的已完成任务列表。completedTasks: state => state.tasks.filter(task => task.completed).

突变只应该用于突变你的存储状态。

最后,在action中,你可以与任何你需要的东西进行交互,比如某处的webserver API或 this.$do_something 然后根据结果发射突变来更新状态。

所以我说,Nuxt在这里做的事情是有道理的,要注入动作,但不要注入getters。


0
投票

我也遇到了同样的问题,我可以通过做

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

然而,不知道这在SSR模式下是否有效。

© www.soinside.com 2019 - 2024. All rights reserved.