我是Vue的新手,所以我可能误会了一些东西。我想像这样在本地函数内调用vuex动作App.vue
:
<template>
<div id="app">
<button @click="runFunction(1)">Test</button>
</div>
</template>
<script>
import { mapActions } from 'vuex'
export default{
data() { return { } },
methods: {
...mapActions(['doAction']),
buttonClicked: (input) => { runFunction(input) }
}
}
function runFunction(input){
doAction({ ID: input });
}
</script>
该动作将导致 store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
export default new Vuex.Store({
state: {
IDs: []
},
mutations: {
doAction: (state, id) => { state.IDs.push(id) }
},
actions: {
doAction: ({ commit }, id) => { commit('doAction', id) }
}
})
我也有一个main.js来设置vue:
import Vue from 'vue'
import App from './App.vue'
import store from './store'
new Vue({
el: '#app',
store,
render: h => h(App)
})
我得到的错误是:
ReferenceError: doAction is not defined
at runFunction
如何在函数内调用映射的动作?版本是Vue 2.6.10
定义runFunction
为“局部函数”存在几个问题:
function runFunction(input){
doAction({ ID: input });
}
首先,这只是一个普通的JavaScript函数,并且适用通常的作用域规则。doAction
需要在此函数可以看到的地方定义。在此函数和中定义的组件之间没有魔术链接App.vue
。该功能将可供组件中的代码访问,例如in中buttonClicked
,但反之则不可。
下一个问题是它在模板中不可用。当您runTemplate(1)
在要编写的模板中编写时this.runTemplate(1)
,尝试在当前实例上解决它。您的函数不在当前实例上。鉴于您的模板包括在内,@click="runFunction(1)"
我很惊讶您没有看到控制台错误警告,提示单击处理程序未定义。
mapActions
使用中保存的引用来访问商店this.$store
。将该引用添加store
到时,就会创建该引用new Vue({store})
。这家商店似乎看起来很神奇,但实际上只是this.$store
,this
当前组件在哪里。
目前还不清楚为什么要尝试在组件外部编写此函数。最简单的解决方案是将其添加到中methods
。然后,它会提供给模板,你可以访问doAction
作为this.doAction
。
要将其保留为单独的功能,您需要为它提供对商店的某种访问权限。首先不知道为什么要将其分开,目前尚不清楚如何最好地做到这一点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句