1.Vuex是什么?
- Vuex是为Vue.js开发的状态管理模式
- Vuex解决了不同组件之间数据共享的问题
- Vuex可以实现组件里面数据的持久化
- Vuex的几个核心概念: State Getters Mutations Actions Modules next.vuex.vuejs.org/
2.Vuex的基本使用
- 安装依赖: npm install vuex@next --save
- src目录下新建vuex文件夹,文件夹内新建store.js
- 在store.js中编写代码
import { createStore} from 'vuex'
const store = createStore({
state() {
return {
count: 1
}
},
mutations: {
increment(state) {
state.count ++
}
}
})
export default store;
- main.js/main.ts 中挂在vuex
import store from './vuex/store'
app.use(store)
- 在Home.vue组件中使用state
<template>
<div class="home">
{{count}}
</div>
</template>
//第一种获取state的方法
//通过计算属性,或者直接用this.$store.state.count
computed: {
count() {
return this.$store.state.count
}
}
//第二种获取state的方法: mapState
import { mapState} from 'vuex'
computed: {
...mapState(['count'])
},
如果需要修改变量值,可以写成如下形式:
computed: {
...mapState({
aaa: (state) => {
state.count
}
})
},
//第三种获取state的方法
在组件中引入store 然后使用store.state.count
- 在Home.vue中修改state中的count,此时用到了mutations,需要通过commit
<template>
<div class="home">
{{count}}
<button @click="incCount">自增</button>
</div>
</template>
methods: {
incCount() {
this.$store.commit('increment')
}
}
-
vuex中的getters getter类似计算属性,getter的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生改变才会重新被计算
-store.js中定义getters
const store = createStore({
state() {
return {
count: 1,
msg: 'hello world'
}
},
mutations: {
increment(state) {
state.count ++
}
},
getters: {
reverseMsg: state=> {
return state.msg.reverse()
}
}
})
-Home.vue中访问getter
<template>
<div class="home">
{{revMsg}}
</div>
</template>
//访问getter的第一种方法
//访问getter的第二种方法
computed: {
revMsg() {
return this.$store.getters.reverseMsg
}
}
//访问getter的第三种方法
import { mapGetters} from 'vuex'
computed: {
...mapGetters(['revMsg'])
},
- vuex中的Actions
- Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。 -store.js中定义actions
const store = createStore({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
-Home.vue中通过store.dispatch分发action
//方法1
store.dispatch('increment')
//方法2
this.$store.dispatch('increment')
//方法3
methods: {
...mapActions([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
]),
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
- vuex中的Module 应用的所有状态都定义到store中,会显得比较臃肿,而module解决了这个问题,是代码更加清晰可见
-
定义module,如user.js new.js 里面写入state,getters,mutations,actions等
-
store.js引入已定义的modole
-
使用时采用如下方式
this.$store.news.count
this.$store.user.count
this.$store.commit('reverseMsg')
- 组合式API中使用vux
import {useStore} from 'vuex'
export default defineComponent({
setup(){
const store = useStore
}
})