在 vuex 中访问 Nuxt 插件功能 getter
Accessing Nuxt plugin function in vuex getter
我正在开始使用 nuxtjs 和 vuex。我刚刚在从 getter 访问组合注入插件函数时遇到问题。例如:
nuxt.config.js
...
plugins: [
'~/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
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 文档只展示了从 mutations 和 actions 访问注入的插件函数的例子,但没有明确提到 getters 不能访问插件函数。这在 nuxt 中是否可行,或者是否有充分的理由不在 getter 中调用插件方法?任何帮助表示赞赏。
我遇到了同样的问题,我可以通过
来解决这个问题
export const getters = {
someGetter: state => {
$nuxt.$doSomething("Called from Getter") // Grab $nuxt from the global scope
}
}
但不确定这是否适用于 SSR 模式
你不应该在 getter 中尝试 do_something
。吸气剂仅用于从商店的状态中导出状态。关键是您不必单独存储和保持最新的派生状态。例如,您有一个任务列表,并且您有一个 getter 表示已完成的任务,而不是一个单独的已完成任务列表:completedTasks: state => state.tasks.filter(task => task.completed)
.
突变只能用于改变商店的状态。
最后,在操作中,您可以与您需要的任何东西进行交互,例如某处的网络服务器 API 或 this.$do_something
,然后触发突变以根据结果更新状态。
所以我想说 Nuxt 在这里做的事情是有道理的,注入动作而不是 getters。
我正在开始使用 nuxtjs 和 vuex。我刚刚在从 getter 访问组合注入插件函数时遇到问题。例如:
nuxt.config.js
...
plugins: [
'~/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
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 文档只展示了从 mutations 和 actions 访问注入的插件函数的例子,但没有明确提到 getters 不能访问插件函数。这在 nuxt 中是否可行,或者是否有充分的理由不在 getter 中调用插件方法?任何帮助表示赞赏。
我遇到了同样的问题,我可以通过
来解决这个问题export const getters = {
someGetter: state => {
$nuxt.$doSomething("Called from Getter") // Grab $nuxt from the global scope
}
}
但不确定这是否适用于 SSR 模式
你不应该在 getter 中尝试 do_something
。吸气剂仅用于从商店的状态中导出状态。关键是您不必单独存储和保持最新的派生状态。例如,您有一个任务列表,并且您有一个 getter 表示已完成的任务,而不是一个单独的已完成任务列表:completedTasks: state => state.tasks.filter(task => task.completed)
.
突变只能用于改变商店的状态。
最后,在操作中,您可以与您需要的任何东西进行交互,例如某处的网络服务器 API 或 this.$do_something
,然后触发突变以根据结果更新状态。
所以我想说 Nuxt 在这里做的事情是有道理的,注入动作而不是 getters。