vuex 的基本使用

vuex 的基本使用

人生苦短,不提概念,只谈使用

安装 vuex
npm i vuex --S
创建文件

常用的 vuex 文件路径在 store/index.js

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

Vue.use(Vuex)
export defaule new Vuex.Stroe({
  state: {},
  mutations: {},
  actions: {},
  getters: {}
})
vuestate 的使用

statevuex 的基本数据,用于存储数据

 state: {
    list: {}, // 所有的任务列表
    input_value: '请输入代办事项', // 输入框的内容
    next_id: 5, // 下一个列表项的 id
    view_key: 'all'
  },

vue 页面中使用

<script>
import { mapState } from "vuex";
export default {
  name: "app",
  data() {
    return {};
  },

  computed: {
    // 数组中实在 store/index.js state 中定义的属性
    ...mapState(["input_value", "view_key"]),
  },
  methods: {
    getState() {
      // 直接调用 state 中的值
      this.$store.state.input_value;
    },
  },
};
</script>
mutation 的基本使用

mutation 同步操作,用于更新 state 中的数据

  mutations: {
    // list:页面中修改后传递的数据
    INIT_LIST(state, list) {
      // state 数据存储中的数据,固定形参
        state.list = list
      },
  }

vue 页面中使用

<script>
import { mapMutations } from "vuex";
export default {
  name: "app",
  data() {
    return {};
  },
  methods: {
    ...mapMutations(["INIT_LIST"]),
    getGetter() {
      // 直接调用 action 中的值
      this.$store.commit("INIT_LIST", list);
      // 或者
      this.INIT_LIST(list);
    },
  },
};
</script>
action 的基本使用

action 异步操作,执行context.commit 提交 mutation

    actions: {
    GET_LIST(context,data) {
        context.commit('INIT_LIST', data)
    }
  },

vue 页面中使用

<script>
import { mapActions } from "vuex";
export default {
  name: "app",
  data() {
    return {};
  },
  methods: {
    ...mapAction(["GET_LIST"]),
    getGetter() {
      // 直接调用 action 中的值
      this.$store.dispatch("GET_LIST", data);
      // 或者
      this.GET_LIST(data);
    },
  },
};
</script>
getter 的基本使用

gettervuex 中的计算属性

    getters: {
    // 计算属性
    UN_DONE_LENGTH(state) {
      return (state.list || []).filter((item) => item.done === false).length
    },
    // 展示代办类型
    INFO_LIST(state) {
      let list
      switch (state.view_key) {
        case 'all':
          list = state.list
          break
        case 'undone':
          list = state.list.filter(x => !x.done)
          break
        case 'done':
          list = state.list.filter(x => x.done)
          break
      }
      return list
    }
  },

vue 页面中使用

<script>
import { mapGetters } from "vuex";
export default {
  name: "app",
  data() {
    return {};
  },

  computed: {
    // 数组中实在 store/index.js getter 中定义的属性
    ...mapGetters(["INFO_LIST", "UN_DONE_LENGTH"]),
  },
  methods: {
    getGetter() {
      // 直接调用 getter 中的值
      this.$store.getters.INFO_LIST;
    },
  },
};
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值