vuex实例应用1

vuex是一个专为 Vue.js 应用程序开发的状态管理模式

vuex一般在大中型单页面应用中使用,如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。

安装vuex依赖

cnpm install vuex --save-dev

引用store,store实例也可以写在main.js中,但是考虑项目过大,把store写在main.js中会降低代码可读性,所以单独创建一个store文件来应用vuex(见下文index.js)

  • main.js
import store from './store/index'

创建store,使用vuex状态管理模式

  • index.js
import vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex); //使用vuex
const state = {
      count:1
};

//随着mutations越来越复杂,增加actions用来管理mutations
const actions = {
      add:({commit,state})=>{
            commit('add')
      },
      del:({commit,state})=>{
            commit('del')
      }
};
//用于修改状态
const mutations = {
       add:(state)=>{
          state.coumt++;
       },
       del:(state)=>{
          if(state.count>2){
              state.count--;
          }
       }
};
const store = new vuex.Store({   //创建仓库,仓库中添加state
   state,
   actions,
   mutations
});

//导出store对象
export default store;

设置改变数据状态,渲染数据到视图

Find.js

<template>
    <div>
        <!-- state -->
        {{$store.state.flag}}
        <!--<button @click="$store.state.flag='click'">click</button>-->
        <!--mutations 改变数据的状态-->
        <!--使用$store.commit('abc')会触发mutations中的abc方法-->
        <!--<button @click="$store.commit('abc')">mutations</button>-->
        <!--执行多个mutations 需要actions来进行管理-->
        <!--<button @click="$store.dispatch('abc')">dispatch</button>-->
        <button @click="add">添加</button>
        <button @click="del">删除</button>
        {{count}}
    </div>
</template>

<script>
import {mapState,mapGetters,mapActions} from 'vuex'

export default{
   data(){
     return {
     
     }
   }
   methods:{
      add(){
          this.$store.dispatch('add')
      },
      del(){
          this.$store.dispatch('del')
      }
},
//computed:{  //方法一
//    count2(){
//          return this.$store. state.count
//    }
//},
computed:mapState(['count'])   //获取值方法2
}
</script>

参考文章:

vuex是什么?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值