1. 什么是 Vuex
Vuex 是实现组件全局状态( 数据 )管理的一种机制,可以方便的实现组件之间数据的共享。
2. 使用 Vuex 统一管理状态的好处
- 能够在 Vuex 中集中管理共享的数据,易于开发和后期维护
- 能够高效地实现组件之间的数据共享,提高开发效率
- 存储在 vuex 中的数据都是响应式的,能够实时保持数据与页面的同步
3.用法
1. stroe 文件 : index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
name: 'hello',
},
mutations: {
check(state, val) {
state.name = val
},
},
actions: {
checkLazy(state, val) {
state.commit('check', val)
},
},
getters: {
nickname: (state) => {
return 'nickname ' + state.name
},
},
})
2. 全局引入 store
import store from './store'
Vue.config.productionTip = false
new Vue({
router,
store,
render: (h) => h(App)
}).$mount('#app')
3. 组件内调用:
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export default {
data() {
return {
// nickname: ''
}
},
computed: {
...mapState(['name']),
...mapGetters(['nickname'])
},
created() {
// this.check('world')
// this.check('checkLazy')
const name = this.$store.state.name
const nickname1 = this.$store.getters.nickname
console.log(name)
console.log(nickname1)
// 等价于
// computed: {
// ...mapState['name'],
// ...mapGetters['nickname']
// },
},
methods: {
...mapMutations(['check']),
...mapActions(['checkLazy']),
// 等价于
// checkName() {
// this.$store.commit(check)
// this.$store.dispatch(checkLazy)
// }
},
}