vue中使用vuex

vue中使用vuex (mutations)

一、适合初学者使用,保存数据以及获取数据

1、在store文件夹,新建个index.js文件(命名看个人习惯,如果没有该文件夹,可以新建一个,当然也可以不建文件夹,直接新建个js文件也是可以的)

在新建的js文件中写入如下代码:

import Vue from "vue"
import Vuex from "vuex"
 
Vue.use(Vuex);
 
export default new Vuex.Store({
    state:{
        pathName: "",
    }
    mutations:{
        // 保存当前菜单栏的路径
        savePath(state,pathName){
            state.pathName = pathName;
        },
      
    }
})

2、main.js引用:(注意路径即可)

// 引入vuex-store
import store from './store/index';
 
new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})

3、在组件中保存数据:

methods:{
    click(){
        // 点击按钮进行一些操作,然后保存数据
        this.$store.commit('saveCurrDbSource',this.db)
    }
}

4、获取变量:(当数据初始获取不到时,可以使用计算属性用来获取)

this.$store.state.变量名

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。也就是说,前面两个都是状态值本身,mutations才是改变状态的执行者。
注意:mutations只能是同步地更改状态。

vue中使用vuex (actions)

Action 提交的是 mutation,而不是直接变更状态. Action 是异步的,mutation是同步的。

1.在store.js 中 代码为:

import Vue from 'vue'
import Vuex from 'vuex'
 
//使用vuex模块
Vue.use(Vuex);
 
//声明静态常量为4
const state = {
  count : 4
};
 
const mutations = {
  add(state,n){
    state.count +=n.a;
  },
  sub(state){
    state.count--;
  }
};
 
const actions = {
  //2种书写方式
  addplus(context){ //可以理解为代表了整个的context
    context.commit('add',{a:10}) 
  },
  subplus({commit}){
    commit('sub');
  }

};
 
//导出一个模块
export default new Vuex.Store({
  state,
  mutations,
  actions
})

2.在组件中使用dispatch

template>
 <div id="app">
  <div id="appaaa">
    <h1>这是vuex的示例</h1>
    <p>组件内部count{{count}}</p>
    <p>
      <button @click = "addplus">+</button>
      <button @click = "subplus">-</button>
    </p>
    </p>
  </div>
 </div>
</template>

<script>
    export default {
        methods: {
            addplus(){
                this.$store.dispatch("addplus");第一个参数为action里方法,第二个为要传的参数
            },
            subplus() {
                this.$store.dispatch("subplus")
            }
        }
    }
</script>

高级映射写法

<template>
 <div id="app">
   <div id="appaaa">
    <h1>这是vuex的示例</h1>
    <p>组件内部count{{count}}</p>
    <p>
      <button @click = "addplus">+</button>
      <button @click = "subplus">-</button>
    </p>
    </p>

  </div>
 </div>
</template>

<script>
//引入mapGetters
import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'
export default {
 name:'app',
 data(){
   return {

   }
 },
 computed:{
   ...mapState([
     "count"      代替:this.$store.state.count;
     ]),
 },
 methods:{
   ...mapActions([
      "addplus",// 将 `this.addplus()` 映射为 `this.$store.dispatch('addplus')`
      "subplus"
     ])
 }

}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值