Vuex简单使用

Posted lc123456

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vuex简单使用相关的知识,希望对你有一定的参考价值。

<template>
  <div class="home">
        <!-- {{this.$store.state.count}} -->
           <!-- 这里的count1是从index.js里面的state里面拿出来的 -->
           {{count1}}
     <!-- 可以在事件后面传参数,比如数字1 -->
           <button @click="add(1)">+</button>
           <button @click="jian">-</button>
  </div>
</template>

<script>
import {mapState,mapActions} from "vuex"
export default {
        data(){
            return{
                
            }
         },
         computed:{
            //  count1(){
            //   return this.$store.state.count
            //  }
    //下面这个是用来获取页面count值 注: 使用({})语法
            ...mapState({
                count1:state=>state.count
            })
         },
         methods:{
   //用来向index.js里面的actions传下面这两个事件 注: 使用([])语法
            ...mapActions([
                ‘add‘,
                ‘jian‘
            ])
         }
}
</script>
 
 
//下面是index.js页面
import Vue from ‘vue‘
import Vuex from ‘vuex‘

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count:1
  },
  mutations: {
    add(state,a){
      state.count++;
/
  console.log(a)
    },
    jian(state)
    {
      if(state.count>1)
      {
        state.count--
      }
    }
  },
  actions: {
  //这个地方可以用来接收我们点击的时候事件传过来的参数a 在context后面加逗号写参数就可以
    add(context,a){
      context.commit("add",a)
    },
    jian(context){
      context.commit("jian")
    }
  },
  modules: {
  }
})
//总结 actions用来操作mutations  然后再通过mutations来操作state
 
 

以上是关于Vuex简单使用的主要内容,如果未能解决你的问题,请参考以下文章

Vuex简单使用

vueX的简单使用

vuex简单使用。

vuex详解vue简单使用

vuex的简单使用

VueX 的安装及简单使用