Vue_11_Spa_项目5次-VUEX

Vuex:相当于前端项目的一个数据库(前端数据库),Vuex是管理整个前端项目的变量,可以把它看成一个简单的数据库。

目标:
    1.了解vuex中的各个js文件的用途
    2.利用vuex同步取值
    3.利用vuex取值
    4.Vuex的异步加载问题及后台调用问题

1.vue中各个组件之间传值
    1.父子组件
        父组件-->子组件,通过子组件的自定义属性:props
        子组件-->父组件,通过自定义事件:this.$emit('事件名',参数1,参数2,...);

    2.非父子组件或父子组件
        通过数据总数Bus,this.$root.$emit('事件名',参数1,参数2,...)

    3.非父子组件或父子组件
        更好的方式是在vue中使用vuex

方法1: 用组件之间通讯。这样写很麻烦,并且写着写着,估计自己都不知道这是啥了,很容易写晕。
方法2: 我们定义全局变量。模块a的数据赋值给全局变量x。然后模块b获取x。这样我们就很容易获取到数据

2.Vuex
官方解释:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。可以想象为一个“前端数据库”(数据仓库),
让其在各个页面上实现数据的共享包括状态,并且可操作
   Vuex分成五个部分: 
1.State:单一状态树
2.Getters:状态获取
3.Mutations:触发同步事件
4.Actions:提交mutation,可以包含异步操作
5.Module:将vuex进行分模块

3.vuex使用步骤 

        3.1 安装
                npm install vuex -S

  
     
    3.2 创建store模块,分别维护state/actions/mutations/getters
            store
              index.js
              state.js
              actions.js
              mutations.js
              getters.js

    3.3 在store/index.js文件中新建vuex的store实例,并注册上面引入的各大模块
        const store = new Vuex.Store({state,getters,actions,mutations})

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

3.5 之后按要求编码,即可使用vuex的相关功能
    

4.vuex的核心概念:store、state、getters、mutations、actions
4.0 store
    每一个Vuex应用的核心就是store(仓库),store基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。
    const store = new Vuex.Store({
     state,    // 共同维护的一个状态,state里面可以是很多个全局状态
     getters,  // 获取数据并渲染
     actions,  // 数据的异步操作
     mutations  // 处理数据的唯一途径,state的改变或赋值只能在这里
    })
   4.1 state(保存数据的容器)
    状态,即要全局读写的数据
    const state = {
      resturantName:'飞歌餐馆'
    };
       this.$store.state.resturantName;//不建议

 4.2 getters(getXxx)
     获取数据并渲染,
     const getters = {
       resturantName: (state) => {
         return state.resturantName;
       }
     }; 

     注1:getters将state中定义的值暴露在this.$store.getters对象中,我们可以通过如下代码访问
          this.$store.getters.resturantName
    
     注2:state状态存储是响应式的,从store实例中读取状态最简单的方法就是在计算属性中返回某个状态,如下:
          computed: {
            resturantName: function() {
              return this.$store.getters.resturantName;
            }
          }

  4.3 mutations(setXxx)
      处理数据的唯一途径,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'
          })
           
      注2:一定要记住,Mutation 必须是同步函数。为什么呢?异步方法,我们不知道什么时候状态会发生改变,所以也就无法追踪了
           如果我们需要异步操作,Mutations就不能满足我们需求了,这时候我们就需要Actions了
           mutations: {
            someMutation (state) {
              api.callAsyncMethod(() => {
                state.count++
              })
            }
           } 

  4.4 actions
      数据的异步(async)操作
      如何理解javascript中的异步和同步?附录四:同步和异步的示例代码

5.vuex综合案例
需求:两个组件A和B,vuex维护的公共数据是餐馆名:resturantName,默认值:飞歌餐馆,
那么现在A和B页面显示的就是飞歌餐馆。如果A修改餐馆名称为A餐馆,则B页面显示的将会是A餐馆,反之B修改同理。
这就是vuex维护公共状态或数据的魅力,在一个地方修改了数据,在这个项目的其他页面都会变成这个数据。

6. actions 
export default {
  setResturantNameByAsync: function(context, payload) {
    setTimeout(() => {
      context.commit('setResturantName', payload);//Action提交的是mutation
    }, 3000);
  }
}
   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。


   注1:actions中方法的调用方式语法如下:
        this.$store.dispatch(type,payload);
        例如:this.$store.dispatch('setResturantNameByAsync',{resturantName: '啃德鸡2'});

   注2:action中提交mutation
        context.commit('setResturantName',{resturantName: '啃德鸡2'});

   注3:VUEX 的 actions 中无法获取到 this 对象
        如果要在actions 或者 mutations 中使用this对象。可以在调用的时候把this对象传过去
        {resturantName: '啃德鸡2',_this:this}//this就是在调用时的vue实例      

   Vuex中actions的使用场景
   场景1:部门管理中添加或删除了新的部门,员工新增/编辑页面的部门列表需要进行变化   
   场景2:vuex之使用actions和axios异步初始购物车数据

一.Vuex来源&四大控件&helloworld

第一步下载vuex ,项目根目录执行黑窗口输入: npm install vuex -S

再去项目里面新建一个目录store

目录里面建立四个js文件,分别是State.js、Getters.js、Actions.js、Mutations.js(首字母大写)

里面都先写一行代码:

export default{

}

 再建立一个index.js并写入:(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

1.State使用

State.js

/* 变量定义 */
export default{
      resturantName:'浪琴湾'
}

在main.js里面在写入:

import store from './store'
router,

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'
// 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/>'
})

在VuexPage1.vue写入 :

<template>
    <div>
      <h3>欢迎来到九零年代{{msg}}</h3>
    </div>
</template>

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

      }
    },
    computed:{
      msg(){
        return "YYDS";
      }
    }
  }
</script>

<style>
</style>

 配置VuexPage1路由:

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'

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
        }
      ]
    }
  ]
})

打开Eclipse后台,黑窗口重新执行一下项目

运行结果:

一样的操作建立一个VuePage2.vue

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

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

      }
    },
    computed: {
      msg() {
        return "1937";
      }
    }
  }
</script>

<style>
</style>

 index.js配置好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
        }
      ]
    }
  ]
})

实现点击树形菜单可以来回切换效果:

点击用户管理: 

点击角色管理:

切的是不同的组件

VuexPage1:

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

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

      }
    },
    methods:{
      panta(){
        // this.$router.push();
      }
    },
    computed: {
      msg() {
        // return "YYDS";
        return this.$store.state.resturantName;
      }
    }
  }
</script>

<style>
</style>

 VuexPage2:

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

 这样就实现了两个拿到的都是浪琴湾

2.Mutations.js使用

Mutations.js:

export default {
  setResturantName: (state, payload) => { //payload: 载荷:其实就是一个保存要传递参数的容器,就是一个对象
    state.resturantName = payload.resturantName;
  }
}

VuexPage1.vue:

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

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

      }
    },
    methods:{
      panta(){
        // this.$router.push();
        this.$store.commit("setResturantName",{
          resturantName:"岳麓区"
        })
      }
    },
    computed: {
      msg() {
        // return "YYDS";
        return this.$store.state.resturantName;
      }
    }
  }
</script>

<style>
</style>

此时在1号页面点击盘它,就将两个页面的浪琴湾改成了岳麓区

运行结果:

二、Vuex与后台交互

3.Getters使用:

VuexPage1.vue:

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

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

      }
    },
    methods:{
      panta(){
        // this.$router.push();
        this.$store.commit("setResturantName",{
          resturantName:"岳麓区"
        })
      }
    },
    computed: {
      msg() {
        // return "YYDS";
        // return this.$store.state.resturantName;
        return this.$store.getters.getResturantName;
      }
    }
  }
</script>

<style>
</style>

 去Getters.js里面去定义方法

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

执行结果:

  

点击盘它:两个页面也可以跳去岳麓区

4.Action.js使用:

Action.js:

// 异步修改
export default {
  setResturantNameAsync: (context, payload) => { //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 "YYDS";
        // return this.$store.state.resturantName;
        return this.$store.getters.getResturantName;
      }
    }
  }
</script>

<style>
</style>

两个按钮都点了,两个同时进行,最后的结果跟着异步走的

5.VueX与后台交互:

Mutations.js代码:

// 变量修改
export default {
  setResturantName: (state, payload) => { //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.$root.Bus.$on("collapsed-aside",(v)=>{
        this.collapsed = v;
      });

  }
}

 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",{})
        },
      pantaAsync(){
        this.$store.dispatch("setResturantNameAsync",{
          resturantName:"长沙"
        })
      }
    },
    computed: {
      msg() {
        // return "YYDS";
        // return this.$store.state.resturantName;
        return this.$store.getters.getResturantName;
      }
    }
  }
</script>

<style>
</style>

运行点击vuex与后台交互,会有一个错urls

获取不到Mutations.js里面的urls

 let url = this.axios.urls.SYSTEM_MENU_TREE;

 此时Mutations里面的this跟VuexPage1是不一样的,VuexPage1里面的this此时指的是vue里的根实例,Mutations里面的this指的是Mutations这个文件

methods:{
      panta(){
        // this.$router.push();
        this.$store.commit("setResturantName",{
          resturantName:"岳麓区"
          })
        },

此时在VuexPage1里面的doAjax定义一个_this:

<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//this是vue的根实例,把它当做变量_this,把它传到Mutations.js里面去
          })
        },
      pantaAsync(){
        this.$store.dispatch("setResturantNameAsync",{
          resturantName:"长沙"
        })
      }
    },
    computed: {
      msg() {
        // return "YYDS";
        // return this.$store.state.resturantName;
        return this.$store.getters.getResturantName;
      }
    }
  }
</script>

<style>
</style>

Mutations里面也将this修改为VuexPage1中定义的_this,通过 _this去调用

// 变量修改
export default {
  setResturantName: (state, payload) => { //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);
    });

  }
}

点击vuex与后台交互按钮,如果不报错,就意味着在VueX里面是可以跟后台进行交互的

运行结果:

所以说,在vuex里面是可以去调后台的,只不过要绕个弯,把主界面的this传到vuex里面去,拿不到值得时候就让它拿到。

Bay!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值