vuex的使用

vuex说白了就是vue中的数据管理仓库,为开发者的数据操作,例如购物车类似的操作,带来了极大的便捷,最近也在使用vuex整理了如下的学习心得,希望能帮大家解决问题.

vuex的基础使用

1.下载好vue.js和vuex.js文件,并引入到html页面中去

2.对vuex的基础配置

 

const store = new Vuex.Store({ 
        state:{ 
            count:0
        },
        mutations:{
            increment:function (state) {
                state.count++;
            },
            descrement:function (state) {
                state.count--
            }
        }
    });

 

store是新创建vuex中对的store对象

state是专门来管理数据的仓库

mutations是用来处理各种判断,异步请求,流程控制,也就是说要干什么事情,在这里监听了两个action名,只有接受到相对应的action名,就会触发函数,对state中的count进行操作

3.html代码

<div id="app">
    count的值:{{count}}
    <p><button @click="increment">count加1</button></p>
    <p><button @click="descrement">count减1</button></p>
    <p><button @click="checkAsyncAdd">延迟加1</button></p>
    <p><button @click="checkAsyncOdd">延迟减1</button></p>
    <p></p>
</div>

每一个按钮绑定一个事件,实现对count的改变

4.vue实例中代码的编写

    new Vue({
        computed:{
            count(){
                return store.state.count
            }
        },
        methods:{
            increment:function () {
                store.commit("increment")
            },
            descrement:function () {
                store.commit("descrement")
            },
            checkAsyncAdd:function () {
               setTimeout(function () {
                   store.commit("increment")
               },1000)
            },
            checkAsyncOdd:function () {
                setTimeout(function () {
                    store.commit("descrement")
                },1000)
            }
        }
    }).$mount("#app")

使用计算属性来实时元素标签更新对state.count中的引用,(因为state是一个对象,那么count就是其属性,所以在vuex的store中count变化,由于是地址引用,那么count就在全局进行变化)

increment函数执行通过store中的commit属性发送"increment"action名,就可以实现了state中count的改变,其他的方法类似

 

在vue项目中使用vuex

1没有安装vuex就使用cnpm/npm i vuex -D  安装好vuex

2.创建store.js文件(随便创建在哪个目录下,我推荐跟main.js在同一目录下),设置如下内容

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex); //全局使用vuex
const state = { //定义数据仓
  count :10
};
const mutations = { //处理数据(状态)变化
  ydb(state){  //"ydb"和"ydb1"都是action名
    state.count++;
  },
  ydb1(state){
    state.count--;
  }
};
const actions= {
  increment:({commit})=>{  //"increment"是接受前端页面传过来的事件名,下面的也是
      commit("ydb") //发送actions名,下面类似
  },
  descrement:({commit})=>{
    console.log(arguments);
    commit("ydb1");
  },
  checkOdd:({commit,state})=>{
    if(state.count%2===0){
      commit("ydb")
    }
  },
  checkAsync:({commit})=>{
   new Promise((resolve)=>{
     setTimeout(function () {
       commit("ydb");
       resolve();
     },1000)
   })
  }
};
const getters = { //设置仓库数去获取对象,方便页面获取仓库中的值
  count:function () {
    return state.count
  }
};
export default new Vuex.Store({ //导出一个新的vuex.Store对象
  state,
  actions,
  mutations,
  getters
  //并返回定义好的各种功能对象,注意名称必须按照我这样子写,如state写成states会报错
})

 

3 在项目主文件main.js中引入vuex

import Vue from 'vue'
import App from './App.vue'
//import Loading from './components/loading/index'
import store from  './store' //引入创建好的store对象
//Vue.use(Loading);
new Vue({
  store,
  el: '#app',
  render: h => h(App)
})

4.APP.vue文件中编写如下代码

<template>
  <div id="app">
   <p @click="get">welcome to 蚂蝗俱乐部</p>
    <Loading ></Loading>
    {{count}}
    <p><button @click="increment">count加1</button></p>
    <p><button @click="descrement">count减1</button></p>
    <p><button @click="checkOdd">偶数才能点击+</button></p>
    <p><button @click="checkAsync">点击异步+</button></p>
  </div>
</template>

<script>
import {mapGetters,mapActions} from "vuex" //通过es6中的语法,对vuex进行解构赋值,注意名称必须这样写 关于es6的更多介绍,请查看我其他随笔
export default {
  name: 'app',
  data () {
    return {}
  },
  computed: { //第一种写法:获取在main.js中全局使用store中state中count的值
    ...mapGetters([
      'count'
    ])
  },
//  computed:mapGetters( //第二种写法:作用同上
//      ['count']
//  ),
  methods: {
    ...mapActions([ //第一种写法:向store对象中的actions发送事件名
      'increment', 'descrement', "checkOdd", "checkAsync"
    ]),
    get(){
      alert(1)
    }
  },
//  methods:mapActions([ //第二种写法:向store对象中的actions发送事件名
//      'increment', 'descrement', "checkOdd", "checkAsync"
//    ]),
  
}
</script>
<style>
</style>

vuex模块化

个人感觉使用vue项目中使用vuex的方法,所有东西都在store.js中,这样页面显的比较代码拥堵,在官网中,作者提供了vuex模块化的思路,自己也把上面的代码改造了一下,实现了一个小的demo

1.在vue项目中创建store文件夹,创建如下文件

actions.js相当于之前的actions对象,用来监听不同的事件名来发送不同的actions名

import * as types from './types' //导入actions名集合
import state from './module'//导入数据仓库
export default { //到处一个发送actions名的对象
  increment:({commit})=>{ //"increment"为前端页面在mapActions中传递过来的事件名,监听到就发送对应的actions名,下面的类似
    commit(types.YDB);
  },
  descrement:({commit})=>{
    commit(types.YDB1);
  },
  checkOdd:({commit})=>{
    if(state.count%2===0){
      commit(types.YDB);
    }

  },
  checkAsync:({commit})=>{
    new Promise((resovle)=>{
      setTimeout(function () {
        commit(types.YDB);
        resovle()
      },1000)
    })

  }
}

  

getters.js相当于之前的getters对象

export default { //返回数据仓库中的count值
  count:(state)=>{
    return state.count
  }
}

  

index就是主文件,负责到处vuex所必须要的配置好之后的对象

import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './actions'
Vue.use(Vuex); //全局使用vuex
export  default new Vuex.Store({
  actions,   
  modules:{
    mutations //这里的mutations里面包含了多个对象,使用modules可以转化格式导出
  }
})
//导出配置好的vuex对象

module.js相当于之前的state对象,用来存放数据,就是一个数据仓库

const state = {
  count:20
};
export default state //导出数据仓库

  

types.js其实在官方中是没有的,但是大多数人的项目中是用的,一般用来放置一些acction名集合

export const YDB = "YDB";
export const YDB1 = "YDB1";

  如上所示,已经成功的把vuex模块化,这样不同的操作,只需要找到不同的js文件就可以进行处理,更符合模块化开发

其中main.js中的内容如下

import Vue from 'vue'
import App from './App.vue'
import Loading from './components/loading/index'
import store from  './store/index' //引入store文件夹中的index主文件
Vue.use(Loading);
new Vue({
  store, //全局使用
  el: '#app',
  render: h => h(App)
})  


//注 APP.vue中的代码没有发生任何改变

 

posted @ 2018-06-28 21:25  只会一点前端  阅读(871)  评论(0编辑  收藏  举报