vuex是:状态管理工具
状态管理就是在多个组件中共享数据,且是响应式的、一个变、全部变
单页面的状态管理
视图层(view)触发操作(action)更改状态(state)响应回视图层(view)
store/index.ts 创建store对象并导出store
import { createStore } from 'vuex'
export default createStore({
state: {
},
getters: {
},
mutations: {
},
actions: {
},
modules: {
}
})
main.js 全局引入并使用store
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
createApp(App).use(store).mount('#app')
1.state
state:vuex的基本数据,用来储存变量
state: {
font_size:100,
font_list:5,
},
在需要使用到vuex的页面中引入
import { useStore } from 'vuex' // 引入useStore 方法
const store = useStore() // 该方法用于返回store 实例
console.log(store) // store 实例对象
//template中
{{$store.state.font_size}}
2.mutations
mutations:提交更新数据方法,必须同步方法(异步必须使用action)
//可以向commit传入额外的参数,即mutation的载荷。
mutations: {
increment(state, n){
state.count += n;
}
}
store.commit('increment', 10);
//data还可以是一个对象。
mutations: {
increment(state, data){
state.count += data.amount;
}
}
store.commit('increment', {amount: 10});
//还可以使用type属性来提交mutation。
store.commit({
type: 'increment',
amount: 10
});
3.actions
actions:和mutations的功能大致相同不同有
(1).actions提交的是mutation,而不是直接改变状态
(2).actions可以包含任何异步操作
...
mutations: {
sum (state, num) {
state.count += num
}
},
actions: {
// context 上下文对象,可以理解为store
sum_actions (context, num) {
setTimeout(() => {
context.commit('sum', num) // 通过context去触发mutions中的sum
}, 1000)
}
}
4.getters
getters:基本数据(state)的派生数据相当于state计算属性
使用 通过$store.getters.方法名
进行调用
5.modules
modules:vuex允许我们将store分割成模块化(modules),而每个模块拥有着自己的state、mutation、action、getters等
在modules中可以创建单一的模块,一个模块处理一个模块的功能
在需要使用的页面中引入就行
在template中模块中的写法和无模块的写法大同小异,带上模块的名称即可
{{$store.state.user.count}}
store.commit('user/sum', num) // 参数带上模块名称
store.dispatch('user/sum_actions', sum)