Vuex的使用

268 阅读1分钟

新建vuex/store.js文件

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const state = {
  name: "zhangsan"
};
//更改状态
const mutations = {
  //1无参
  changeNameToZhangsan(state) {
    state.name = "lisi";
  },
  //2带参数
  changeNameWithParam(state, payload) {
    state.name = payload.name;
  }
};
//异步更改状态
const actions = {
  //无参
  changeNameAsync(context) {
    let _name = context.state.name;
    setTimeout(() => {
      context.commit("changeNameToZhangsan");
    }, 1000);
  },
  //有参
  changeNameWithParamAsync(context, payload) {
    setTimeout(() => {
      context.commit("changeNameWithParam", payload);
    }, 1000);
  }
};

//getters条件判断选择后续操作
const getters = {
    //无参
    formatterName: state => {
        let postfix= "";
        if(state.name == "zhangsan"){
            postfix = "nice";
        };
        return state.name+" "+postfix;
    },
    //有参
    customFormatterName: (state) => (val) => {
        let postfix = "";
        if(state.name == "zhangsan"){
            postfix = val;
        };
        return state.name+" "+postfix;
    }
}

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

main.js

import store from "./vuex/store";//引入store.js
new Vue({
  el: "#app",
  router,
  store,//相当于store:store,注册后,子组件时可以使用this.$store访问
  components: { App },
  template: "<App/>"
});

demo.vue

<template>
  <div>
    <div>store中的姓名:{{ this.$store.state.name }}</div>
    <div>
      <button @click="setNameDefault()">不带参数设置lisi</button>
    </div>
    <input type="text" v-model="name" />
    <button @click="setNameAsync()">带参数设置</button>
    <div>
      <p>无参</p>
      <p>{{ this.$store.getters.formatterName }}</p>
      <p>有参</p>
      <p>{{ this.$store.getters.customFormatterName("cool") }}</p>
    </div>
    <div>
      <p>state</p>
      <p>{{ cname1 }}</p>
    </div>
    <div>
      <p>getter</p>
      <p>{{ customFormatterName("cool") }}</p>
    </div>
    <button @click="getMock()">mock测试请求</button>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions, mapGetters } from "vuex";
export default {
  name: "HelloWorld",
  data() {
    return {
      name: ""
    };
  },
  computed: {
    ...mapState({
      //state=>mapState  状态管理
      cname: "name",
      cname1: function(state) {
        return state.name + "111";
      }
    }),
    ...mapGetters([
      //getter=>mapGetters 条件选择
      "formatterName",
      "customFormatterName"
    ])
  },

  methods: {
    ...mapMutations([
      //mutation=>mapMutations 更改状态
      "changeNameToZhangsan"
    ]),
    ...mapActions({
      //action=>mapActions 异步
      changeNameWithParamAsync1: "changeNameWithParamAsync"
    }),
    setNameDefault() {
      this.changeNameToZhangsan();
    },
    getMock(){//mock调用
      this.$axios({
          url:'/parameter/query',
          method: "get",
        }).then(res =>{
        console.log(res.data);
      });
    },
    setNameAsync() {
      this.changeNameWithParamAsync1({
        name: this.name
      });

      // //荷载提交
      // this.$store.dispatch("changeNameWithParamAsync", {
      //   name: this.name
      // });
      // //对象提交
      // this.$store.dispatch({
      //   type: "changeNameWithParamAsync", //固定的
      //   name: this.name
      // });
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>