vuex的使用方法

npm install vuex -s
在src下创建store,文件夹下创建index.js

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
    state:{
        count: 0
    },
    getters:{

    },
    mutations:{
        increment (state) {
            state.count++
        },
        remove (state) {
            state.count--
        }
        //同步操作,写法:this.$store.commit('mutations方法名',值)
    },
    actions:{
        increment (context) {
            context.commit('increment')
        }
       //含有异步操作,例如向后台提交数据,写法: this.$store.dispatch('action方法名',值)
    }
});
 
export default store;

在组件获取vuex的数据

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>{{this.$store.state.count}}</h2>
    <h2>{{count1}}</h2>
     <div ref="getText">Add "scoped" attribute to limit CSS to this component only</div>
     <!-- <button @click="dome">获取ref属性</button> -->
     <button @click="increment">vuex加</button>
     <button @click="remove">vuex减</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  computed:{
     ...mapState({
        count1: state=>state.count * 88
     }),
    // ...mapMutations([
    //   'increment',
    //   'remove'
    // ])

  },
  methods: {
    dome () {
      console.log(this.$refs.getText)
      /* eslint-disable */
    },
    ...mapMutations([ //this.$store.commit简写方法
      'increment',
      'remove'
    ]),
    ...mapActions([
      'increment', // map `this.increment()` to `this.$store.dispatch('increment')`
      //含有异步操作,例如向后台提交数据,写法: this.$store.dispatch('action方法名',值)
    ]),
    // increment() {
    //   let n = 2;
    //   this.$store.commit('increment',n)//同步操作,写法:this.$store.commit('mutations方法名',值)
    //   console.log(this.$store.state.count,n)
    // },
    // remove () {
    //   this.$store.commit('remove')//同步操作,写法:this.$store.commit('mutations方法名',值)
    // }
  }
}
</script>
<style scoped>

</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值