Vue基本用法:vuex、axios 拦截器和vue-router路由导航守卫

vuex 中有5个属性:state, mutations, actions, getters,modules.

vuex 中修改 state属性中值的唯一方法就是提交 mutation,但 mutations 是同步方法, actions 是异步方法

 

在项目中安装 vuex:

npm i vuex -S

vuex 的流程图:

 

 

示例代码:

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'
import App from './App'
import router from './router'

Vue.config.productionTip = false


// 1、引入 vuex 
import Vuex from 'vuex'

// 2、在模块化开发中,需要在开头 use 一下
Vue.use(Vuex)

// 3、创建商店
const store = new Vuex.Store({
  state:{
    num: 1    // 通过 computed 把 num 监听起来; 注意:不要直接修改 state 中的值,更改state的唯一方法是提交 mutation(commit方法)
  },
  mutations: {
    // mutations 中的方法默认有一个参数叫 state

    syncMutaAddNum(state,val){
      state.num += val;   // 直接修改 state
    },

    asyncMutaAddNum(state, val){
      state.num += val;   // 同步操作放在 mutations 中
    }
  },
  actions:{
    // actions 中的方法默认有一个参数 context, 这个 context 就是store 实例
    // actions 类似于 mutation,不同在于:1. action 提交是的 mutation,而不是直接变更状态;2. action 可以包含任意异步操作

    syncActionAddNum(context, val){
      // 在 actions 中去 commit mutations 中的方法
      context.commit('syncMutaAddNum', val);    // commit mutations 中的方法
    },

    asyncActionAddNum(context, val){
      setTimeout(()=>{     // setTimeout 是一个异步函数;异步操作放到 actions 中
        context.commit('asyncMutaAddNum', val);
      }, 1000)    // 每隔1秒去执行一下回调函数
      
    }
  }

  // 同步操作在 mutaions 中做, 异步操作在actions 中做

  /*
  state 中有一些状态,主要在组件之间传值的时候, 通过 computed 把 state关联于相关组件;
  想要个性state中的数据,需要通过 dispatch 来分发 actions 中的方法,actions 中去 commit mutations 中的方法,mutations 中的方法直接去修改 state 中的状态
  */ 
})



/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  // 把商店 store 挂载到 Vue 上
  store,  // 在组件中使用 store 时,可通过 this.$store 来获取
  components: { App },
  template: '<App/>'
})

App.vue 中 (里面的代码和 vuex 无关)

<template>
  <div id="app">
    <div class="header">
      <ul>
        <li v-for="item in navList" :key="item.id">
          <router-link :to='{name: item.name}'>{{ item.title }}</router-link>
        </li>
      </ul>
    </div>
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App',
  data(){
    return {
      navList:[
        {id:1,title:'首页',name:'Home'},
        {id:2,title:'课程',name:'Course'}
      ]
    }
  }
}
</script>

<style>

</style>

router 中的 index.js 省略

components 中的 Home.vue (利用 computed 把 组件和 state 关联起来,如 监听 state 中的数据)

<template>
  <div>
      我是首页
      <h1>我是父组件Home中的num:{{ myNum }}</h1>
      <Son />
  </div>
</template>

<script>

// 把 Son 这个组件导入到 Home 组件中
import Son from './Son'

export default {
    name:'Home',

    components:{
      Son   // 把导入的 Son 组件挂载到 Home 组件上
    },

  computed:{
    // computed 属性监听 store 中的state属性
    myNum: function () {
      return this.$store.state.num    // this.$store 能获取到“商店”是因为继承
    }
  },

}
</script>

<style>

</style>

components 中的 Son.vue (包含 dispatch actions 中的方法)

<template>
  <div>
      我是子组件
      <h2>我是子组件中的 num: {{ mySonNum }}</h2>
      <button @click="syncAddNum">同步+1</button>
      <button @click="asyncAddNum">异步+5</button>
  </div>
</template>

<script>
export default {
    name: 'Son',
    methods:{
      syncAddNum(){
        // 通过 dispatch 去分发 actions 中的方法
        this.$store.dispatch('syncActionAddNum', 1);
      },

      asyncAddNum(){
        this.$store.dispatch('asyncActionAddNum', 5);
      }
    },
    computed:{
    // computed 属性监听 store 中的state属性
      mySonNum: function () {
        return this.$store.state.num    // this.$store 能获取到“商店”是因为继承
      }
    }
}
</script>

<style>

</style>

浏览器效果示例:

 

参考链接:https://vuex.vuejs.org/zh/guide/actions.html 

 

axios 请求拦截器

axios 请求拦截器能够在每个请求发出去之前对该请求进行处理,如自定义请求头,如下所求:

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么,如添加请求头
    config.headers.Authorization = 'Bear 8329vna9wnvu9'    // 自定义请求头

    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// config,指发送请求之前的配置对象

上述代码添加到 restful/api.js 中即可。 api.js 中是所有 axios 请求相关的代码

参考链接:

http://www.axios-js.com/zh-cn/docs/

https://blog.csdn.net/weixin_44867717/article/details/110495253

 

vue-router 全局导航守卫

可以使用 router.beforeEach 注册一个全局前置守卫 ,这样当前端路由每次发生变化时, router.beforeEach 都会被调用。可以在这个全局导航守卫中判断 cookie 是否已经存在并执行相应的操作。

在 main.js 中添加如下示例代码:

// 全局导航守卫,判断cookie 是否已经存在
router.beforeEach((to, from, next) => {
  // 执行相应的操作
  if(VueCookies.isKey('access_token')){
    // 如对登陆传信息进行设置
  }

  next();   // next 方法一定要执行,要不然页面会卡住
})

 

官方文档:

https://router.vuejs.org/zh/guide/advanced/navigation-guards.html#%E5%85%A8%E5%B1%80%E5%89%8D%E7%BD%AE%E5%AE%88%E5%8D%AB 

 

posted @ 2021-02-01 00:57  neozheng  阅读(728)  评论(0编辑  收藏  举报