如何去从头搭建一个vue项目(二)

140 阅读2分钟

如何去从头搭建一个项目?

一、配置axios

前面我们已经安装过了axios,下面开始配置。 在main.js中引入axios。

import axios from 'axios';
Vue.prototype.axios = axios;

具体配置信息可参考该作者blog.csdn.net/weixin_4425…

或者axios中文文档:www.kancloud.cn/yunye/axios…

或者这位博主的www.jianshu.com/p/dacbefd62…

整体配置

import store from "./store";
import axios from "axios";
// 提示信息
import {
    Message
} from 'element-ui'

// axios配置
axios.defaults.baseURL = store.state.baseUrl;
// 请求拦截器,对请求信息做的统一处理
axios.interceptors.request.use(
    // config是为请求提供的配置信息
    (config) => {
        // 发送请求钱做些什么
        console.log('config', config);
        return config
    },
    error => {
        // 对请求错误的接口做些什么
        return Promise.reject(error)
    }
)
// 响应拦截器,对接口的返回数据做统一的处理
axios.interceptors.response.use(
    (res) => {
        // 对对应数据返回值做不同处理
        if (res.status == 200) {
            const data = res.data;
            // token
            if (data.Code == -1) {
                // 浏览器里缓存的数据全清掉
                localStorage.clear();
                // 关闭所有实例
                Message.closeAll();
                // 提示信息
                Message({
                    showClose: true,
                    message: data.Message,
                    type: "error",
                    duration: 1000,
                });
                // 返回到登录页
                setTimeout(() => {
                    location.href = "/#/login";
                }, 1000)
            } else if (data.Code == -2) {
                location.href = "/#/login";
            }
            return data;
        } else {
            return res
        }
    },
    // 响应de错误
    function (error) {
        // 关闭所有实例
        Message.closeAll();
        Message({
            showClose: true,
            message: "请求数据出错",
            type: "error",
            duration: 2000,
        })
        return Promise.reject(error)
    }
)

二、router配置

2.1、在src下创建utils文件(工具文件夹),里面放置一些常用的公共方法。下面是根据官网简单配置,具体的操作之后再说。

在utils中创建permission.js文件


import router from "../router";
import store from "../store";

// 白名单
const whiteList = []

/**
 * 权限设置  全局前置守卫,守卫是异步解析执行。  
 * 有两个参数:to 将要进入的地址,from:当前导航要离开的路由
 * 可选的第三个参数 next
 * 在这种情况下,确保 next 在任何给定的导航守卫中都被严格调用一次
 * */ 
router.beforeEach((to, from, next) => {
    // ....
    
    //返回false,以取消导航 
    return false
})

在main.js中引入 import './utils/permission'

页面空白问题

当我引入permission后,打开项目页面显示为空白,这是因为,前置路由守卫的问题,因为当我打开项目,跳转到登录页时,此时状态一直为未登录,所以它会一直跳转到 login 然后死循环,页面就一直是空白的. 解决:

router.beforeEach((to, from, next) => {
    // ....
    if (to.path === '/login' || to.path == '/') {
        next()
    } else {
        next()
    }
})

这里有些小问题,登录跳转后,进入的页面没有显示东西,打了断点后排查问题,结果是没有找到进入的页面,其实是router.js中,路由path填写粗心,没有写"/"。改正后就显示正常了。

接下来,就可以开始搭建项目页面的骨架了。