记一次vue仿网易云音乐的单页面应用

栏目: 编程语言 · 发布时间: 7年前

内容简介:一直想做一个基于VUE的项目,但是因为项目往往要涉及到后端的知识(不会后端真的苦),所以就没有一直真正的动手去做一个项目。直到发现GitHub上有网易云音乐的api仅仅完成了首页,登入,歌单,歌曲列表页。

说明

一直想做一个基于VUE的项目,但是因为项目往往要涉及到后端的知识(不会后端真的苦),所以就没有一直真正的动手去做一个项目。

直到发现GitHub上有网易云音乐的api NeteaseCloudMusicApi ,才开始动手去做。

仅仅完成了首页,登入,歌单,歌曲列表页。

前端技术栈

vue2+vuex+vue-router+axios+mint-ui+webpack

遇到的问题

1.前端路由拦截

想做一个登录拦截,验证没有登录之前,就跳转到登录页面

解决方法是:通过http response 拦截器判断token(本地的cookie)判断

创建一个http.js

import axios from 'axios'
import store from './store/store'
import * as types from './store/types'
import router from './router/index'

// axios 配置
axios.defaults.timeout = 5000
axios.defaults.baseURL = 'https://api.github.com'

// http request 拦截器
axios.interceptors.request.use(
  config => {
    if (store.state.xsrfCookieName) {
      config.headers.Authorization = `xsrfCookieName ${store.state.xsrfCookieName}`
    }
    return config
  },
  err => {
    return Promise.reject(err)
  },
)

// http response 拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 401 清除token信息并跳转到登录页面
          store.commit(types.LOGOUT)
          
          // 只有在当前路由不是登录页面才跳转
          router.currentRoute.path !== 'login' &&
            router.replace({
              path: 'login',
              query: { redirect: router.currentRoute.path },
            })
      }
    }
    // console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
    return Promise.reject(error.response.data)
  },
)

export default axios

2.路由懒加载

{
      path:'/my',
      name:'my',
       meta:{
        requireAuth:true,
      },
      component:resolve=>{
        Indicator.open('加载中...');
        require.ensure(['@/views/my'], () => {
          resolve(require('@/views/my'))
          Indicator.close()
        })
      }
    },

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Visual Thinking

Visual Thinking

Colin Ware / Morgan Kaufmann / 2008-4-18 / USD 49.95

Increasingly, designers need to present information in ways that aid their audiences thinking process. Fortunately, results from the relatively new science of human visual perception provide valuable ......一起来看看 《Visual Thinking》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具