vuex一个模块使用另一个模块的state值
时间: 2023-03-31 11:04:27 浏览: 60
可以通过在第一个模块的getters中引用第二个模块的state值来实现。具体来说,可以在第一个模块的getters中使用rootState参数来获取根状态对象,然后再通过rootState来访问第二个模块的state值。例如:
```
// 第一个模块的getters
const getters = {
someGetter: (state, getters, rootState) => {
return rootState.secondModule.someStateValue;
}
}
```
这样就可以在第一个模块中使用第二个模块的state值了。
相关问题
模块化vuex怎么获取模块里面的值
在使用模块化的 Vuex 中,获取模块里面的值需要使用模块命名空间(module namespace)。
在定义模块时,可以通过 `namespaced: true` 开启模块命名空间,这样在获取模块内部的状态、getters、mutations、actions 时,就需要加上模块的命名空间。
举个例子,假设我们有一个 `user` 模块,其中定义了一个 `state`:
```javascript
// user.js
export default {
namespaced: true,
state: {
name: '小明',
age: 18
}
}
```
如果要在另一个模块中获取 `user` 模块的 `name` 值,可以这样写:
```javascript
// other.js
export default {
computed: {
userName() {
return this.$store.state.user.name
}
}
}
```
但是在使用模块命名空间后,就需要添加模块命名空间前缀:
```javascript
// user.js
export default {
namespaced: true,
state: {
name: '小明',
age: 18
}
}
// other.js
export default {
computed: {
userName() {
return this.$store.state.user.name // 错误,需要加上模块命名空间前缀
// return this.$store.state['user'].name // 正确的方式
}
}
}
```
如果需要在 getters、mutations、actions 中访问模块内部的状态和其他函数,也需要加上模块命名空间前缀,例如:
```javascript
// user.js
export default {
namespaced: true,
state: {
name: '小明',
age: 18
},
getters: {
getNameAndAge(state) {
return `${state.name} - ${state.age}`
}
},
mutations: {
setName(state, newName) {
state.name = newName
}
},
actions: {
changeName({ commit }, newName) {
commit('setName', newName)
}
}
}
// other.js
export default {
computed: {
nameAndAge() {
return this.$store.getters['user/getNameAndAge'] // 获取 user 模块的 getters
}
},
methods: {
changeName(newName) {
this.$store.commit('user/setName', newName) // 调用 user 模块的 mutation
this.$store.dispatch('user/changeName', newName) // 调用 user 模块的 action
}
}
}
```
以上就是在模块化 Vuex 中获取模块里面的值的方法。
写一个uniapp使用vuex的模板
好的,以下是一个Uniapp使用Vuex的模板:
1. 在根目录下创建一个store目录,里面包含一个index.js文件和一个modules目录。
2. 在index.js文件中引入Vue和Vuex,创建一个Vuex实例并导出。
3. 在modules目录中创建一个模块,例如app.js,在其中定义state、mutations、actions和getters。
4. 在index.js文件中导入该模块,并使用Vue.use(Vuex)注册Vuex插件。
5. 在App.vue中引入store,并在Vuex.Store选项中传入该store实例。
index.js文件示例:
```
import Vue from 'vue'
import Vuex from 'vuex'
import app from './modules/app'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
app
}
})
export default store
```
app.js文件示例:
```
const state = {
count: 0
}
const mutations = {
increment(state) {
state.count++
}
}
const actions = {
increment({ commit }) {
commit('increment')
}
}
const getters = {
getCount: state => state.count
}
export default {
namespaced: true,
state,
mutations,
actions,
getters
}
```
App.vue文件示例:
```
<template>
<div>
<h1>{{ count }}</h1>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
export default {
computed: {
...mapGetters('app', ['getCount']),
count () {
return this.getCount
}
},
methods: {
...mapActions('app', ['increment'])
}
}
</script>
<style>
</style>
```