Vuex:状态管理工具
有时候,需要在多个组件中共享状态,并且是响应式的状态,一个变,全都跟着发生改变的场景。
例如,一些全局要用的的状态信息:用户登录状态、用户信息等等;
这时候,就需要这样的一个工具来进行全局的状态管理,而 Vuex
就是这样的一个工具。
store/index.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
export default new Vuex.Store({
state:{
},
actions:{
},
mutaions:{
},
modules:{
},
getters:{
}
)}
Vue3
里面基本上都是工厂函数,从 vue
变成 createApp
, store
也封装成为了一个函数:createStore
,如下所示:
src/store/index.ts:
// vue3中创建store实例对象的方法createStore()按需引入
import {
createStore } from 'vuex'
export default createStore({
state: {
},
mutations: {
},
actions: {
},
getters: {
},
modules: {
}
})
state
类似于 vue
中的 data
,用于存放数据模型;
getters
类似于 vue
中 computed
,相当于 state
的计算属性;
mutations
类似于 vue
中的 method
,只有通过它的方法函数可以改变 state
的值,而且,它的方法函数必须是同步,不能是异步;
actions
:只能通过它来调用 mutations
来改变 state
的值,它的函数方法可以是异步的;
modules
:可以引入多个 module
,通过这个属性,可以添加多个 module
进入 Vuex
的 store
中。
src/main.ts:
import {
createApp } from 'vue'
// 引入Antd
import Antd from 'ant-design-vue'
import router from './router/index'
import store from './store'
import App from './App.vue'
// 样式文件需要单独引入
import 'ant-design-vue/dist/antd.css'
const app = createApp(App)
app.use(Antd)
app.use(store)
app.use(router)
app.mount('#app')
src/store/index.ts:
// vue3中创建store实例对象的方法createStore()按需引入
import {
createStore } from 'vuex'
export default createStore({
// 声明变量
state: {
count: 1
},
mutations: {
// 定义mutations,用于修改状态state(因为state不能直接赋值修改,只能通过mutations进行修改)
updateCount(state,newVal){
state.count = newVal
}
},
actions: {
// 定义actions,mutations的值由actions传入
setCount(context,newVal){
context.commit('updateCount',newVal)
}
},
getters: {
// 定义一个getter
getCount(state){
return state.count
}
},
modules: {
}
})
src/views/TestPage.vue:
<template>
<div>
<h1>vuex数据-state、getters:{
{
$store.getters.getCount}}<