vuex 状态管理

时间:2019-09-16
本文章向大家介绍vuex 状态管理,主要包括vuex 状态管理使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
  • 1.安装vuex :
    • npm i vuex
  • 1.在store里引入vuex:
    • import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex);

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