由于经典模式即将被弃用,我正在尝试将我的商店转移到模块模式。但是我确实想将状态、动作、突变和吸气剂保存在单独的文件中。所以假设我目前只有一个模块 - auth。这是我的商店结构:
store
|_ modules
| |_auth
| |_actions.js
| |_getters.js
| |_mutations.js
| |_state.js
|
|_actions.js
|_auth.js
|_getters.js
|_index.js
|_mutations.js
|_state.js
Run Code Online (Sandbox Code Playgroud)
store\modules\auth\state.js
目前只有一个属性:
store
|_ modules
| |_auth
| |_actions.js
| |_getters.js
| |_mutations.js
| |_state.js
|
|_actions.js
|_auth.js
|_getters.js
|_index.js
|_mutations.js
|_state.js
Run Code Online (Sandbox Code Playgroud)
这是 store\modules\auth\getters.js
export const state = () => {
return {
token: null
}
}
Run Code Online (Sandbox Code Playgroud)
然后在我的store\auth.js
:
export const getters = {
isAuthenticated(state) {
return !!state.token
}
}
Run Code Online (Sandbox Code Playgroud)
最后在我的store\index.js
我只有这个代码:
import {actions} from './modules/auth/actions'
import {getters} from './modules/auth/getters'
import {mutations} from './modules/auth/mutations'
import {state} from './modules/auth/state'
export {
actions,
getters,
mutations,
state
}
Run Code Online (Sandbox Code Playgroud)
这给了我以下错误:
[vuex] getters should be function but "getters.getters" in module "modules.auth" is {}.
我已经挠了几个小时了,不知道如何解决这个问题。
我试图做这样的事情,例如:
export const getters = () => {
return {
isAuthenticated: state => !!state.token
}
}
Run Code Online (Sandbox Code Playgroud)
那确实编译了,但在控制台中它抛出了另一个错误:
[vuex] unknown getter: auth/isAuthenticated
它也给了我这个警告:
store/modules/auth/state.js should export a method that returns an object
在那里我以为我这样做了......
有什么想法吗?
终于设法解决了。也许有人会发现它有帮助。
首先,我的getter导出是错误的。这是正确的做法:
export default {
isAuthenticated(state) {
return !!state.token
}
}
Run Code Online (Sandbox Code Playgroud)
关于国家的同样事情:
export default () => ({
token: null
})
Run Code Online (Sandbox Code Playgroud)
然后我不得不将auth
模块从modules
文件夹移动到文件夹下store
。我也删除了index.js
和auth.js
文件。
store
|_auth
| |_actions.js
| |_getters.js
| |_mutations.js
| |_state.js
|
|_actions.js
|_getters.js
|_mutations.js
|_state.js
Run Code Online (Sandbox Code Playgroud)
现在一切正常!
归档时间: |
|
查看次数: |
659 次 |
最近记录: |