Vuex 状态管理

1. 什么是 Vuex

Vuex 是实现组件全局状态( 数据 )管理的一种机制,可以方便的实现组件之间数据的共享。

2. 使用 Vuex 统一管理状态的好处

  1. 能够在 Vuex 中集中管理共享的数据,易于开发和后期维护
  2. 能够高效地实现组件之间的数据共享,提高开发效率
  3. 存储在 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)
    // }

  },

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值