vuex

首先安装vuex

npm install vuex --save

在src下新建store文件夹

再新建index.js、state.js、getters.js、mutations.js、mutations-types.js、actions.js文件

//index.js
import Vue from 'vue'
import Vuex from 'vuex'
import * as actions from './actions'
import * as getters from './getters';
import state from './state';
import mutations from './mutations';

Vue.use(Vuex)

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})

  

//state.js
const state = {
  currentIndex: 0,
}

export default state;

  

//getters.js
export const currentIndex = state => state.currentIndex;

  

//mutations.js
import * as types from './mutations-types';
const mutations = {
  [types.SET_CURRENT_INDEX] (state, currentIndex) {
    state.currentIndex = currentIndex;
  },
}
export default mutations;

  

//mutations-types.js
export const SET_CURRENT_INDEX = 'SET_CURRENT_INDEX';

  

//actions.js
import * as types from './mutations-types';
export const orderPlay = function ({ commit }, { index }) {
  commit(types.SET_CURRENT_INDEX, index);
}

  在main.js中

import store from './store'
new Vue({
  store,
  render: h => h(App),
}).$mount('#app')
使用:
//helloworld.vue
<template>
  <div class="hello">
    {{currentIndex}}
    <button @click="add">+</button>
    <button @click="del">-</button>
  </div>
</template>

<script>
import { mapActions, mapMutations, mapGetters } from "vuex";
export default {
  name: 'HelloWorld',
  data () {
    return {
      list: [{
        id: 5
      }]
    }
  },
  computed: {
    ...mapGetters(['currentIndex'])
  },
  methods: {
    ...mapActions(["orderPlay"]),
    ...mapMutations({
      setCurrentIndex: "SET_CURRENT_INDEX",
    }),
    add () {
      this.setCurrentIndex(2)
    },
    del () {
      this.orderPlay(
        {
          index: this.list[0].id
        })
    }
  }
}
</script>

  

posted @ 2021-06-18 15:30  chicidol  阅读(19)  评论(0编辑  收藏  举报