Vue v-module数据保存到vuex

1,066 阅读1分钟

问题

表单dom的数据需要在其他的组件中使用,需要将数据放在vuex中

方法

在 watch 中监听当前组件值的变化,然后用 this.$store.commit("set_valueswitch", p); 提交

  data() {
    return {
      options: [
        {
          value: "0",
          label: "存量客户"
        },
        {
          value: "1",
          label: "当年新增客户"
        }
      ],
      value: "0",
      valueswitch: false,
      mounthDefaultShow: "", // 默认月份
      timeDefaultShow: "" // 默认日期
    };
  },
    watch: {
    value(p) {
      console.log(p);
      this.$store.commit("set_value", p);
    },
    valueswitch(p) {
      console.log(p);
      this.$store.commit("set_valueswitch", p);
    },
    mounthDefaultShow(p) {
      console.log(p);
      this.$store.commit("set_mounthDefaultShow", p);
    },
    timeDefaultShow(p) {
      console.log(p);
      this.$store.commit("set_timeDefaultShow", p);
    }
  },

然后在需要用到的组建中 取vuex中数据

import { mapState } from "vuex";

  computed: {
    ...mapState({
      org_id: state => {
        return state.org_id;
      },
      value: state => {
        return state.value;
      },
      valueswitch: state => {
        return state.valueswitch;
      },
      mounthDefaultShow: state => {
        return state.mounthDefaultShow;
      },
      timeDefaultShow: state => {
        return state.timeDefaultShow;
      }
    })
  },