Vuex第一课

本期目标:

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

             2.利用vuex同步存储

             3.利用vuex取值

             4.Vuex的异步加载问题及后台调用问题

Vuex官方解释:

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。可以想象为一个“前端数据库”(数据仓库),让其在各个页面上实现数据的共享包括状态,并且可操作

 Vuex分成五个部分:

   1.State:单一状态树
   2.Getters:状态获取
   3.Mutations:触发同步事件
   4.Actions:提交mutation,可以包含异步操作
   5.Module:将vuex进行分模块

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

1.传值

第一种:父传子,通过compenetts[pops:['m'] ]

              子传父,子组件中的事件注册一个新的时间

第二种:总线的概念传值,但是用父子传值的方式,进行开发的话,代码会非常大

2.vuex结构

结构关系:

           state 用于集中管理整个Vue项目中的所有变量

           getters(用于取值),操作变量相当于get方法

           mutations,actions(修改变量值),操作变量相当于set方法

注:actions是mutations的升级版,mutations操作变量里,是同步操作,

       actions是异步操作变量

 3.vuex使用步骤

第一步:安装

(spa1工程所在的根目录下执行命令窗口并且输入 : npm install vuex -S

 第二步:创建store模块,分别维护State/Actions/Mutations/Getters

第三步:store/index.js文件中新建vuexstore实例,并注册上面引入的各大模块

 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

二.vuex取值

要使用vuex,就在mian.js中导入并使用store实例

// 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'
//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 */
/* 绑定了index.html的边界 */
new Vue({
  el: '#app',
  data(){
    return {
      Bus:new Vue({

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

根据使用的表设计,建立组件VuexPage1.vue  VuexPage2.vue

 配置VuexPage1和VuexPage2的路由

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Login from '@/views/Login'
import Reg from '@/views/Reg'
import AppMain from '@/components/AppMain'
import LeftNav from '@/components/LeftNav'
import TopNav from '@/components/TopNav'
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
        }

      ]
    }

  ]
})
 

this.$store.state.resturantName;//不建议使用

于是推荐以下这个方法来取值

Getters.js

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

VuexPage1.vue

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
    }
  },
  methods:{
    pata(){
this.$store.commit("setResturantName",{
  resturantName:"卓小京便利店"
})
    }
  },
  computed:{
    msg(){
     // return this.$store.state.resturantName;
     return this.$store.getters.getResturantName;
    }
  }
}
</script>

 三.Vuex存值

Mutations.js

export default {
       /*    payload:官方给它还取了一个高大上的名字:载荷,其实就是一个保存要传递参数的容器 */
 setResturantName:(state, payload)=>{
  state.resturantName=payload.resturantName;
}
}

VuexPage1.vue

 <script>
export default {
  name: 'HelloWorld',
  data () {
    return {
    }
  },
  methods:{
    pata(){
this.$store.commit("setResturantName",{
  resturantName:"卓小京便利店"
})

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

展示“盘她”的运行结果: 

 

四.Vuex的同步异步 

Action.js

export default{
   setResturantNameAsync:(context,payload) =>{
     //context等价于this.$store,也就是它代表了Vuex的上下文
     //在这个文件中是可以调用同步文件mutations.js定义的同步方法
     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.$router.push();
    this.$store.commit("setResturantName",{
      resturantName:"卓小京便利店"
    })
    },
    pantaAsync(){
      this.$store.dispatch("setResturantNameAsync",{
        resturantName:"卓小京大饭店堂"
      })

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

<style>
</style>
 

 

 

 五.vuex与后台服务器数据交互

Mutations.js

export default {
       /*    payload:官方给它还取了一个高大上的名字:载荷,其实就是一个保存要传递参数的容器 */
 setResturantName:(state, payload)=>{
  state.resturantName=payload.resturantName;
},
doAjax: (context, 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)
            });
 
}
}

vuexpage1.vue

<template>
  <div>
    <h3>页面1:欢迎来到{{msg}}</h3>
    <button @click="panta">盘她</button>
   <button @click="pantaAsync">大Boss</button>
    <button @click="doAjax">vuex与后台交互</button>
  </div>
</template>

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

    }
  },
  methods:{
    panta(){
    // this.$router.push();
    this.$store.commit("setResturantName",{
      resturantName:"卓小京便利店"
    })
    },
    doAjax(){
    // this.$router.push();
    this.$store.commit("doAjax",{
      _this:this
    })

    },
    pantaAsync(){
      this.$store.dispatch("setResturantNameAsync",{
        resturantName:"卓小京大饭店堂"
      })
    }
  },
  computed:{
    msg(){
      // return "KPC";
      return this.$store.getters.getResturantName;
    }
  }
}
</script>

<style>
</style>
 

 

点击ajax与后台交互则会报错:

 解决:在vuexpage1.vue添加_this

doAjax(){
  this.$store.commit("doAjax",{
_this:this
  })
  }

Mutations.js

export default {
       /*    payload:官方给它还取了一个高大上的名字:载荷,其实就是一个保存要传递参数的容器 */
 setResturantName:(state, payload)=>{
  state.resturantName=payload.resturantName;
},
doAjax: (context, payload) => {
  //需求:想在当前的文件中与后台服务器做数据交互
 let _this=payload._this;
  let url = _this.axios.urls.SYSTEM_MENU_TREE;
     _this.axios.post(url,{}).then((resp) => {
              console.log(resp);
              }).catch(function(error) {
              console.log(error)
            });

}
}

展示效果: 

注:拿到数据,证明vuex可以调用后台 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值