Vuex.

一、Vuex来源及四大控件

 

1.了解vuex中的各个js文件的用途

官方解释:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。

可以想象为一个“前端数据库”(数据仓库),
让其在各个页面上实现数据的共享包括状态,并且可操作

作用:用来管理整个spa项目

Vuex主要由四部分组成: 
   1.State:单一状态树
   2.Getters:状态获取
   3.Mutations:触发同步事件
   4.Actions:提交mutation,可以包含异步操作

下载vuex 

语句:npm install vuex -S

 在src中新建store目录        在目录下新建js文件

注:新建js文件名须与四个组件名一样且首字母须大写

State.js 管理、定义变量

Mutation.js 同步改变state容器里的变量值

Action.js 异步改变state容器里的变量值

Getters.js 获取state容器里的变量值

index.js文件将四个控件整合到一起 导出一个store对象 vue根实例中绑定使用(vuex)

当vue实例想要使用vuex时,将index.js导入main.js中

src/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

main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
//开发环境下才会引入mock.js
//开发环境:true&&require('@/mock')会执行后面代码,也就是说mock.js会被导入到当前环境中
//生产环境:false && require('@/mock')不执行后面代码,也就是说mock.js是不会引导到当前环境中
// process.env.MOCK && require('@/mock')
import 'element-ui/lib/theme-chalk/index.css' //新添加2
import App from './App'
import router from './router'
import ElementUI from 'element-ui' //新添加1
import axios from '@/api/http'  //#vue项目对axios的全局配置  
// import axios from 'axios'    
import VueAxios from 'vue-axios'
import store from './store'

Vue.use(ElementUI)   //新添加3
Vue.use(VueAxios,axios)
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  data(){
    return{
      Bus:new Vue({

      })
    }
  },
  router,
  store,
  components: { App },
  template: '<App/>'
})
 

2.vuex传值

3.利用vuex同步取值

在sys中新建两个vue文件

 VuexPage1.vue

<template>
  <div>
    <h3>页面1:欢迎来到{{msg}}</h3>
    <button @click="panta">盘它</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {

    }
  },
  methods:{
    panta(){
      this.$store.commit("setResturantName",{
        resturantName:"浪琴餐馆"
      })
    }
  },
  computed:{
    msg(){
      // return "kfc";
      // return this.$store.state.resturantName;
      return this.$store.getters.getResturantName;
    }
  }
}
</script>

<style>
</style>


 VuexPage2.vue

<template>
  <div>
    <h3>页面2:欢迎来到{{msg}}</h3>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {

    }
  },
  computed:{
    msg(){
      return  this.$store.state.resturantName;
    }
  }
}
</script>

<style>
</style>

src/router/index.js

import VuexPage1 from '@/views/sys/VuexPage1'
import VuexPage2 from '@/views/sys/VuexPage2'


        {
          path: '/sys/VuexPage1',
          name: 'VuexPage1',
          component: VuexPage1
        },
        {
          path: '/sys/VuexPage2',
          name: 'VuexPage2',
          component: VuexPage2
        }

 State.js

export default{
  resturantName:"飞歌餐馆"
}

Mutations.js

export default{
  setResturantName:(state,payload)=>{
    state.resturantName=payload.resturantName;
  }
}

Getters.js

export default{
  getResturantName:(state)=>{
    return state.resturantName;
  }
}

效果展示:

 

 二、Vuex与后台交互

1.利用vuex取值

 Actions.js

export default{
  setResturantNameAsync:(context,payload)=>{
    //context等价于this.$store,也就是他代表了Vuex的上下文
    //在这个文件中可以调用同步文件Mutations.js定义的同步方法
    //this代表了vue根实例   $store代表了vuex的上下文
    setTimeout(function() {
      context.commit("setResturantName",payload);
    }, 6000);
    // state.resturantName=payload.resturantName;
  }
}

VuexPage1.vue

<template>
  <div>
    <h3>页面1:欢迎来到{{msg}}</h3>
    <button @click="panta">盘它</button>
    <button @click="pantaAsync">最大Boss</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {

    }
  },
  methods:{
    panta(){
      this.$store.commit("setResturantName",{
        resturantName:"浪琴餐馆"
      })
    },
    pantaAsync(){
      this.$store.dispatch("setResturantNameAsync",{
        resturantName:"卓京食堂"
      })
    }

  },
  computed:{
    msg(){
      // return "kfc";
      // return this.$store.state.resturantName;
      return this.$store.getters.getResturantName;
    }
  }
}
</script>

<style>
</style>
 

2.后台交互

错误写法:

======Mutations.js中的代码======
export default{
  setResturantName:(state,payload)=>{
    state.resturantName=payload.resturantName;
  },
  doAjax:(state,payload)=>{
    //需求:在当前的文件中与后台服务器做数据交互
    let url=this.axios.urls.SYSTEM_MENU_TREE;
    this.axios.post(url,{}).then((resp)=>{
      console.log(resp);
      this.menus=resp.data.result;
    }).catch(function(error){
      console.log(error);
    });
    //箭头函数解决了this指针污染问题
    this.$root.Bus.$on("collapsed-aside",(v)=>{
      this.collapsed=v;
    });
  }
}

======VuexPage1.vue中的代码======
doAjax(){
      this.$store.commit("doAjax",{})
    }

报错:不能读取urls属性


正确写法:

======Mutations.js中的代码======
export default{
  setResturantName:(state,payload)=>{
    state.resturantName=payload.resturantName;
  },
  doAjax:(state,payload)=>{
    //需求:在当前的文件中与后台服务器做数据交互
    let _this=payload._this;
    let url=_this.axios.urls.SYSTEM_MENU_TREE;
    _this.axios.post(url,{}).then((resp)=>{
      console.log(resp);
      _this.menus=resp.data.result;
    }).catch(function(error){
      console.log(error);
    });
  }
}

======VuexPage1.vue中的代码======
doAjax(){
      this.$store.commit("doAjax",{
        _this:this
      })
    }

payload:载荷,其实就是一个保存要传递参数的容器

效果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值