使用Vuex 实现标签数字增加与减小

1. 若安装了命令行工具 ,可以使用命令创建项目

vue create XXX

2.安装vuex

npm install vuex

3.组织目录结构(自己看需要)

4.代码部分

vuex 和 React中的redux一样,是一个集中state管理工具

4-1 首先需要在main.js 引入,然后挂在到Vue实例上

import Vue from 'vue'
// import App from './App.vue'
import App2 from './App2.vue'

import store from './vuex'

Vue.config.productionTip = false

Vue.use(store)

new Vue({
  render: h => h(App2),
  store
}).$mount('#app')

4-2 创建store实例

import Vue from 'vue';
import Vuex from 'vuex';
import mutations from './mutations'
import state from './state'

Vue.use(Vuex);

const store = new Vuex.Store({
  state,
  mutations
});
export default store;

4-3 编写state

export default{
  count:0
}

4-4 编写mutations

export default{

  increaseCount(state){
    state.count++;
  },

  plusCount(state){
    state.count--;
  }
}

4-5 在页面中触发事件 store.commit("increaseCount")//函数名,参数模型

<template>
  <div id="app">
    <h1>{{this.$store.state.count}}</h1>
    <button type="button" name="button1" @click="increaseCount">点我增加</button>
    <button type="button" name="button2" @click="plusCount">点我减小</button>
  </div>
</template>

<script>

import store from './vuex'

export default {

  name: 'App2',
  components: {

  },
  methods:{
    increaseCount(){
      store.commit("increaseCount")//函数名,参数模型
    },
    plusCount(){
      store.commit("plusCount")//函数名,参数模型
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
此文仅为鄙人学习笔记之用,朋友你来了,如有不明白或者建议又或者想给我指点一二,请私信我。liuw_flexi@163.com/QQ群:582039935. 我的gitHub: (学习代码都在gitHub) https://github.com/nwgdegitHub/
原文地址:https://www.cnblogs.com/liuw-flexi/p/13607123.html