Vuex

一、Vuex简介 

解决了前端组件传参的问题,针对当前项目所有的变量进行统一管理,可以理解为前端的数据库

Vuex分为五个部分

  1.State:单一状态树

   2.Getters:状态获取

   3.Mutations:触发同步事件

   4.Actions:提交mutation,可以包含异步操作

   5.Module:将vuex进行分模块

二、Vuex版本问题及store.js的使用

1、安装

安装最新版本: npm install vuex -S

2、创建store模块,分别维护state/actions/mutations/getters

index.js
state.js
actions.js
mutations.js
getters.js 

 3、在store/index.js文件中新建vuex的store实例

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'
Vue.use(Vuex)
const store = new Vuex.Store({
 	state,
 	getters,
 	actions,
 	mutations
 })

 export default store

4、在main.js中导入并使用store实例

import store from './store'

      new Vue({
el: '#app',
router,
store, //在main.js中导入store实例
components: {
App
},
template: '<App/>',
data: {
//自定义的事件总线对象,用于父子组件的通信
Bus: new Vue()
}
      })

三、Vuex中的异步同步操作

处理数据的唯一途径,state的改变或赋值只能在这里

  export default {
    // type(事件类型): 其值为setResturantName
    // payload:官方给它还取了一个高大上的名字:载荷,其实就是一个保存要传递参数的容器
    setResturantName: (state, payload) => {
      state.resturantName = payload.resturantName;
  }
  注1:mutations中方法的调用方式
       不能直接调用this.$store.mutations.setResturantName('KFC'),必须使用如下方式调用:
       this.$store.commit(type,payload);

       // 1、把载荷和type分开提交
       store.commit('setResturantName',{
         resturantName:'KFC'
       })

       // 2、载荷和type写到一起
      store.commit({
        type: 'setResturantName',
        resturantName: 'KFC'
      })

一定要记住,Mutation 必须是同步函数。为什么呢?异步方法,我们不知道什么时候状态会发生改变,所以也就无法追踪了
如果我们需要异步操作,Mutations就不能满足我们需求了,这时候我们就需要Actions了
mutations: {
someMutation (state) {
api.callAsyncMethod(() => {
state.count++
})
}
}
异步加载:
Action类似于 mutation,不同在于:
1.Action提交的是mutation,而不是直接变更状态
2.Action可以包含任意异步操作
3.Action的回调函数接收一个 context 上下文参数,注意,这个参数可不一般,它与 store 实例有着相同的方法和属性
但是他们并不是同一个实例,context 包含:
1. state、2. rootState、3. getters、4. mutations、5. actions 五个属性
所以在这里可以使用 context.commit 来提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。

四、Vuex后台交互

action.js

let _this = payload._this;
    let url=_this.axios.urls.SYSTEM_MENU_TREE;
    _this.axios.post(url,{}).then(r=>{
      console.log(r)
    }).catch(e=>{

    });

 vuePage1:

 _this:this

1、router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import AppMain from '@/components/AppMain'
import LeftNav from '@/components/LeftNav'
import TopNav from '@/components/TopNav'
import Login from '@/views/Login'
import Reg from '@/views/Reg'
import Articles from '@/views/sys/Articles'
import VuexPage1 from '@/views/sys/VuexPage1'
import VuexPage2 from '@/views/sys/VuexPage2'

Vue.use(Router)

export default new Router({
  routes: [{
      path: '/',
      name: 'Login',
      component: Login
    },
    {
      path: '/Login',
      name: 'Login',
      component: Login
    },
    {
      path: '/Reg',
      name: 'Reg',
      component: Reg
    },
    {
      path: '/AppMain',
      name: 'AppMain',
      component: AppMain,
      children: [{
          path: '/LeftNav',
          name: 'LeftNav',
          component: LeftNav
        },
        {
          path: '/TopNav',
          name: 'TopNav',
          component: TopNav
        },
        {
          path: '/sys/Articles',
          name: 'Articles',
          component: Articles
        },
        {
          path: '/sys/VuexPage1',
          name: 'VuexPage1',
          component: VuexPage1
        },
        {
          path: '/sys/VuexPage2',
          name: 'VuexPage2',
          component: VuexPage2
        }
      ]
    }
  ]
})

2、store/action.js

export default {
  setResNameAsync: (context, payload) => {
    // 异步修改值 在异步方法中调用了同步方法
    // context指的是Vuex的上下文,相当于 this.$store
    // 此代码6s后执行
    setTimeout(function(){
      context.commit("setResName",payload);
    },6000);

    let _this = payload._this;
    let url=_this.axios.urls.SYSTEM_MENU_TREE;
    _this.axios.post(url,{}).then(r=>{
      console.log(r)
    }).catch(e=>{

    });
  }
}

3、store/getters.js

export default{
  getResName:(state)=>{
    return state.resName;
  }
}

4、store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'
Vue.use(Vuex)
const store = new Vuex.Store({
 	state,
 	getters,
 	actions,
 	mutations
 })

 export default store

5、store/mutations.js

export default{
  setResName:(state,payload)=>{
    // state对象就对应了state.js中的对象
    // payload截荷 对应的 传递的 json对象参数{name:zs,age:12}
    state.resName = payload.resName;
  }
}

6、store/state.js

export default{
  resName:'aaa'
}

7、views/sys/VuexPage1.vue

<template>
  <div>
    <p>
      页面1:欢迎来到{{msg}}
    </p>
    <button @click="buy">盘它</button>
    <button @click="buyAsync">最终店长</button>
  </div>
</template>

<script>
  export default{
    name:'VuexPage1',
    data(){
      return {
      }
    },
    methods:{
      buy(){
        console.log(this.$store);
        // 通过commit方法会调用mutations.js文件中定义好的方法
        this.$store.commit("setResName",{
          resName:'KFC'
        })
      },
      buyAsync(){
        this.$store.dispatch("setResNameAsync",{
          resName:'麦当劳',
          _this:this
        })
      }
    }
    ,
    computed:{
      msg(){
        // 从vuex的state文件中获取值
        // return this.$store.state.resName;//不推荐,不安全
        // 通过getter.js文件获取state.js中定义的变量值
        return this.$store.getters.getResName;
      }
    }
  }
</script>

<style>
</style>

8、views/sys/VuexPage1.vue

<template>
  <div>
    <p>
      页面2:欢迎来到{{msg}}
    </p>
    <button @click="buy">盘它</button>
  </div>
</template>

<script>
  export default{
    name:'VuexPage1',
    data(){
      return {
      }
    }
    ,
    computed:{
      msg(){
        // 从vuex的state文件中获取值
        // return this.$store.state.resName;//不推荐,不安全
        // 通过getter.js文件获取state.js中定义的变量值
        return this.$store.getters.getResName;
      }
    }
  }
</script>

<style>
</style>

 ​​​​​​​​​​​​​​

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值