2.2 如何在Vue中使用Vuex

一、安装Vuex

  1. 新建一个Vue工程

    1. vue create vuex-demo

  2. 安装Vuex

    1. npm i vuex

  3. 启动项目

  4. 在项目中添加Vuex

    1. 找到main.ja文件

      import Vuex from 'vuex'
      
      Vue.use(Vuex)
  5. 代码:

    // vue文件
      <div id="app">
        {{count}}
        <br>
        {{$store.getters.doubleCount}}
        <button @click="$store.commit('increment', 2)">count++</button>
        <button @click="$store.dispatch('increment', 2)">count++</button>
      </div>
    
    //vue下的count
      computed: {
        count() {
          return this.$store.state.count
        }
      }
    
    
    // js代码
    const store = new Vuex.Store({
      // 定义
      state: {
        count: 0,
      },
      // 方法
      mutations: {
        increment(state, num) {
          state.count += num
        }
      },
      // 异步
      actions: {
        increment({state}) {
          setTimeout(()=> {
            state.count++
          }, 2000)
        }
      },
      // 缓存属性,类似计算属性
      getters: {
        doubleCount(status) {
          return status.count * 2
        }
      }
    })

详细代码:

Last updated