vuex 状态管理

  • 1.安装vuex :
    • npm i vuex
  • 1.在store.js里引入vuex ,注册vuex:
    • import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex);
  • 3.定义数据
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);

// 1. 存数据
var state = {
   count: 1
}
//  2.方法 改变state里面的数据
var mutations = {
   inCount() { //加
       ++state.count
   },
   inCount_() { //减
       --state.count
   }
}

//实例化vuex.store

const store = new Vuex.Store({
   state,
   mutations
})
export default store;
  • 3.获取state里面的数据
    • {{this.$store.state.count}}
  • 4.获取方法
    • incCount(){ this.$store.commit('inCount') }

store.js

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);

// 1. 存数据
var state = {
    count: 1
}
//  2.方法 改变state里面的数据
var mutations = {
    inCountAdd() { //加
        ++state.count
    },
    inCount_() { //减
        --state.count
    }
}

//实例化vuex.store
const store = new Vuex.Store({
    state,
    mutations
})
export default store;

home.vue

<template>
  <div class="hello">
    home
    {{this.$store.state.count}}
    <button @click="incCount">增加</button>
  </div>
</template>

<script>
import store from "../vuex/store";

export default {
  methods: {
    incCount() {
      this.$store.commit("inCountAdd");//增加
    }
  },
  store,
  data() {}
};
</script>

<style scoped>
</style>

new.vue

<template>
  <div>
    {{this.$store.state.count}}
    <br />
    <button @click="icCoount_">减</button>
  </div>
</template>

<script>
import store from "../vuex/store";
export default {
  store,
  methods: {
    icCoount_() {
      this.$store.commit("inCount_");//减
    }
  }
};
</script>

<style lang="scss" scoped>
</style>

转载于:https://www.cnblogs.com/divtab/p/11529089.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值