一、安装vuex
npm install vuex@next
二、配置vuex
import { createApp } from 'vue'
import App from './App.vue'
import store from './store' // 导入 storeconst app = createApp(App)
app.use(store) // 使用 store
app.mount('#app')
三、使用vuex
1、各部分的作用
- State 用于存储数据
- Mutations 用于同步修改状态
- Actions 用于异步操作
- Getters 用于派生状态
- Modules 用于模块化管理大型应用
2、State 的使用:
// 在组件中获取状态
import { useStore } from 'vuex'export default {setup() {const store = useStore()// 直接读取状态console.log(store.state.myState)console.log(store.state.isshow)// 通过计算属性监听状态const currentState = computed(() => store.state.myState)return { currentState }}
}
3、Mutations 的使用:
// 在组件中调用 mutations
import { useStore } from 'vuex'export default {setup() {const store = useStore()// 修改状态store.commit('changeState', { value: '即将上映' })store.commit('changeIsShow', { value: true })// 在方法中使用const toggleShow = () => {store.commit('changeIsShow', { value: !store.state.isshow })}return { toggleShow }}
}
4、Getters 的使用
// 在组件中使用 getters
import { useStore } from 'vuex'export default {setup() {const store = useStore()// 使用 getterconsole.log(store.getters.myStateUpper)console.log(store.getters.myStateWithPrefix('当前状态'))}
}
5、Actions 的使用
// 在组件中使用 actions
import { useStore } from 'vuex'export default {setup() {const store = useStore()// 调用异步 actionstore.dispatch('changeStateAsync', { value: '即将上映' })// 调用带条件的 actionstore.dispatch('toggleShowWithCondition')}
}
Modules 的使用
// 在组件中使用 module
import { useStore } from 'vuex'export default {setup() {const store = useStore()// 获取模块状态console.log(store.state.movie.movieList)// 调用模块的 mutationstore.commit('movie/setMovieList', [])// 调用模块的 actionstore.dispatch('movie/fetchMovies')}
}
store.js :
import { createStore } from 'vuex'const movieModule = {namespaced: true,state: {movieList: []},mutations: {setMovieList (state, list) {state.movieList = list}},actions: {async fetchMovies ({ commit }) {// 模拟获取电影列表const movies = await fetch('/api/movies')commit('setMovieList', movies)}}
}export default createStore({state: {myState: '状态管理',isshow: false},getters: {// 获取状态的大写形式myStateUpper: state => {return state.myState.toUpperCase()},// 获取带前缀的状态myStateWithPrefix: state => prefix => {return `${prefix}: ${state.myState}`}},mutations: {changeState (state, data) {console.log('changeState', data)state.myState = data.value},changeIsShow (state, data) {state.isshow = data.value}},actions: {// 异步修改状态async changeStateAsync ({ commit }, data) {// 模拟 API 请求await new Promise(resolve => setTimeout(resolve, 1000))commit('changeState', data)},// 带条件的操作toggleShowWithCondition ({ commit, state }) {if (state.myState !== '') {commit('changeIsShow', { value: !state.isshow })}}},modules: {movie: movieModule}
})
四、调试工具
vue devtools