vuex的简单使用

App.vue

<template>
  <div id="app">
    <h1>现在一共有{{catCount}}只小猫咪,连起来一共{{height}}cm。
    </h1>
    <input type="button" value="增加1只小猫咪" @click="addOneCat"/>
    <input type="button" value="每0.25秒增加1只小猫咪" @click="add1Cat"/>
  </div>
</template>

<script>
import {mapState,mapGetters} from 'vuex'
export default {
  //获取store对象获取state的值,但是遇到获取多个数值时显得比较繁复,可以使用mapState获取的方式
  //   computed:{
  //   catCount:function(){
  //     return this.$store.state.amount;
  //   },
  //   height:function(){
  //     return this.$store.getters.height;
  //   }
  // },

  //mapState获取数值的方式(需要导入mapState依赖,其他类型同)
  computed:{
    ...mapState({
      //如果是被【({})】括起来,则需要通过赋值方式使用
      catCount:state=>state.amount
    }),
    ...mapGetters([
      //如果是被【([])】括起来,则可以直接通过写字符串数组获取到值
      //但前提是所有映射的计算属性名称与store使用的子节点名称相同
      'height','amountType'
    ])
  },

  methods:{
    addOneCat:function(){
      this.$store.commit('add');
      //调用mutations内的方法,需要使用this.$store.commit('function');
          },
    add1Cat:function(){
      this.$store.dispatch('addAmount');
      //调用actions内的方法,需要使用this.$store.dispatch('function');
    }
  }
}
</script>
<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: cent[]er;
  color: #2c3e50;
}

#nav {
  padding: 30px;
}

#nav a {
  font-weight: bold;
  color: #2c3e50;
}

#nav a.router-link-exact-active {
  color: #42b983;
}
</style>

index.js

import Vue from 'vue'
import Vuex from 'vuex'
import sub from './sub'

Vue.use(Vuex)

export default new Vuex.Store({
  //核心对象,所有元素都存在这个实例内
  state: {
    //用于存储共同的数据
    amount:0
  },
  getters: {
    //类似于Computed,用于存放一些数据计算的简单操作
    height:function(state){
      return state.amount*30;
    },
    amountType:function(sub){
      return sub.state.amountType;
    }
  },
  mutations: {
    //用于存放一些改变state内值的方法
    //适合存放只是操作数据的方法
    add(state){
      state.amount++;
    }
  },
  actions: {
    //用于存放一些调用mutations内方法的方法
    //适合存放异步操作的方法
    addAmount({commit}){
      //不可以直接调用mutations内的方法,因为方法不属于methods
      //通过对象的方法触发,commit是隐式传递的
      //如果括号内传递的是{context},通过context.commit也可以调用commit函数
      setInterval(function(){
        commit('add');
      },250);
    }
  },
  modules: {
    //对store.js进行拆分管理,去引入其他的整合模块
    sub
  }
})

sub.vue

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    amountType:'小猫咪'
  }
})
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容