Vuex简介+使用

1、Vuex的理解:

Vuex是为Vue.js 应用程序开发的状态管理模式,集中式存储管理所有组件的状态。

可理解为对要共享的data,进行集中式的管理。

核心:store仓库,包含着应用中大部分的状态

基本对象:
state:存储状态(变量)
getters:对数据获取之前的再次编译,可以理解为state的计算属性。我们在组件中使用 $sotre.getters.fun()
motations:修改状态,同步的,在组件中使用$store.commit('',params)。可以理解为组件中的自定义事件。
actions:异步操作。在组件中使用是$store.dispath(''),提交的是motations。
modules:store的子模块,每个模块有自己的state、getter、motation、action。

2、Vuex的使用

  • 安装依赖
yarn add vuex
或者
npm install -save vuex
  • 导入工程

入口组件<App/>中,绑定store

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");

导入vuex并创建Store对象(store.ts文件)

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

Vue.use(Vuex);
//状态管理(集中管理需要共享的data)

export default new Vuex.Store({
  //存储状态(变量)
  state: {
    count: 0
  },
  //修改状态,同步的,在组件中使用$store.commit('',params)
  mutations: {
    mutationsAddCount(state, n = 0) {
      return (state.count += n);
    },
    mutationsReduceCount(state, n = 0) {
      return (state.count -= n);
    }
  },
  //异步操作。在组件中使用是$store.dispath('')
  actions: {
    actionsAddCount(context, n = 0) {
      console.log(context);
      return context.commit("mutationsAddCount", n);
    },
    actionsReduceCount({ commit }, n = 0) {
      return commit("mutationsReduceCount", n);
    }
  },
  getters: {
    getterCount(state) {
      return (state.count += 5);
    }
  }
});

引用Store对象(*.vue文件中)

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h3>{{ $store.state.count }}</h3>
    <div>
      <button @click="handleAddClick(10)">增加</button>
      <button @click="handleReduceClick(10)">减少</button>
    </div>
    <div>异步操作</div>
    <div>
      <button @click="handleActionsAdd(10)">异步增加</button>
      <button @click="handleActionsReduce(10)">异步减少</button>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";

@Component
export default class HelloWorld extends Vue {
  @Prop() private msg!: string;

  handleAddClick(n: Number) {
    this.$store.commit("mutationsAddCount", n);
  }
  handleReduceClick(n: Number) {
    this.$store.commit("mutationsReduceCount", n);
  }
  handleActionsAdd(n: Number) {
    this.$store.dispatch("actionsAddCount", n);
  }
  handleActionsReduce(n: Number) {
    this.$store.dispatch("actionsReduceCount", n);
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">

</style>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值