vue 2、router|vuex|api

vue-router

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/* router.js */

import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue' // 引入 Home 组件
import About from './views/About.vue' // 引入 About 组件

Vue.use(Router) // 注册路由

export default new Router({
routes: [{
path: '/',
name: 'home',
component: Home
}, {
path: '/about',
name: 'about',
component: About
}]
})
  • 如果路由存在二级目录,需要添加base属性,否则默认为”/“
  • 默认路由模式是hash模式,会携带#标记,与真是url不符合,可以还未history模式
  • 页面组件没有进行按需加载,可以使用require.ensure()来进行优化
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    /* router.js */

    import Vue from 'vue'
    import Router from 'vue-router'

    // 引入 Home 组件
    const Home = resolve => {
    require.ensure(['./views/Home.vue'], () => {
    resolve(require('./views/Home.vue'))
    })
    }

    // 引入 About 组件
    const About = resolve => {
    require.ensure(['./views/About.vue'], () => {
    resolve(require('./views/About.vue'))
    })
    }

    Vue.use(Router)

    let base = `${process.env.BASE_URL}` // 动态获取二级目录

    export default new Router({
    mode: 'history',
    base: base,
    routes: [{
    path: '/',
    name: 'home',
    component: Home
    }, {
    path: '/about',
    name: 'about',
    component: About
    }]
    })
  • 当然,处理使用reauire.ensure来拆分代码,Vue Router官方文档还推荐使用动态import 愈发来进行代码分块
    1
    2
    3
    4
    5
    // 引入 Home 组件
    const Home = () => import('./views/Home.vue');

    // 引入 About 组件
    const About = () => import('./views/About.vue');
  • 如果你想给拆分出的文件命名,可以尝试一下webpack提供的Magic Comments(魔法注释)
    1
    const Home = () => import(/* webpackChunkName:'home'*/ './views/Home.vue');

    Vuex配置

  • vue-cli 生成的store
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    import Vue from 'vue'
    import Vuex from 'vuex'

    Vue.use(Vuex)

    export default new Vuex.Store({
    state: {

    },
    mutations: {

    },
    actions: {

    }
    })
  • 主要是4个核心点
  1. state 存放变量 this.$store.state 获取
  2. getters 计算变量 计算state后返回 this.$store.getter || mapGetters 获取
  3. mutations 修改state值唯一的办法是派发 mutaion this.$store.commit()
  4. actions 派发actions 可以异步派发mutaion this.$store.dispatch(actions)
  5. modules 划分模块引入
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    /* moduleA.js */

    const moduleA = {
    state: {
    text: 'hello'
    },
    mutations: {
    addText (state, txt) {
    // 这里的 `state` 对象是模块的局部状态
    state.text += txt
    }
    },

    actions: {
    setText ({ commit }) {
    commit('addText', ' world')
    }
    },

    getters: {
    getText (state) {
    return state.text + '!'
    }
    }
    }

    export default moduleA
  • a模块引入
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    /* index.js */

    import Vue from 'vue'
    import Vuex from 'vuex'
    import moduleA from './modules/moduleA'
    import moduleB from './modules/moduleB'
    import { mutations } from './mutations'
    import actions from './actions'

    Vue.use(Vuex)

    export default new Vuex.Store({
    state: {
    groups: [1]
    },
    modules: {
    moduleA, // 引入 A 模块
    moduleB, // 引入 B 模块
    },
    actions, // 根级别的 action
    mutations, // 根级别的 mutations

    // 根级别的 getters
    getters: {
    getGroups (state) {
    return state.groups
    }
    }
    })

    接口配置

  • 简单封装ajax
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    /* http.js */
    import 'whatwg-fetch'

    // HTTP 工具类
    export default class Http {
    static async request(method, url, data) {
    const param = {
    method: method,
    headers: {
    'Content-Type': 'application/json'
    }
    };

    if (method === 'GET') {
    url += this.formatQuery(data)
    } else {
    param['body'] = JSON.stringify(data)
    }

    // Tips.loading(); // 可调用 loading 组件

    return fetch(url, param).then(response => this.isSuccess(response))
    .then(response => {
    return response.json()
    })
    }

    // 判断请求是否成功
    static isSuccess(res) {
    if (res.status >= 200 && res.status < 300) {
    return res
    } else {
    this.requestException(res)
    }
    }

    // 处理异常
    static requestException(res) {
    const error = new Error(res.statusText)

    error.response = res

    throw error
    }

    // url处理
    static formatQuery(query) {
    let params = [];

    if (query) {
    for (let item in query) {
    let vals = query[item];
    if (vals !== undefined) {
    params.push(item + '=' + query[item])
    }
    }
    }
    return params.length ? '?' + params.join('&') : '';
    }

    // 处理 get 请求
    static get(url, data) {
    return this.request('GET', url, data)
    }

    // 处理 put 请求
    static put(url, data) {
    return this.request('PUT', url, data)
    }

    // 处理 post 请求
    static post(url, data) {
    return this.request('POST', url, data)
    }

    // 处理 patch 请求
    static patch(url, data) {
    return this.request('PATCH', url, data)
    }

    // 处理 delete 请求
    static delete(url, data) {
    return this.request('DELETE', url, data)
    }
    }
  • 创建一个api集合文件
    1
    2
    3
    4
    5
    6
    7
    /* moduleA.js */
    import Http from './http'

    // 获取测试数据
    export const getTestData = () => {
    return Http.get('https://api.github.com/repos/octokit/octokit.rb')
    }
  • 可以省略 url部分
    1
    2
    3
    4
    5
    6
    7
    /* moduleA.js */
    import Http from './http'

    // 获取测试数据
    export const getTestData = () => {
    return Http.get('/repos/octokit/octokit.rb')
    }
  • 需要配置vue.config.js
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    /* vue.config.js */

    module.exports = {
    ...

    devServer: {

    // string | Object 代理设置
    proxy: {

    // 接口是 '/repos' 开头的才用代理
    '/repos': {
    target: 'https://api.github.com', // 目标地址
    changeOrigin: true, // 是否改变源地址
    // pathRewrite: {'^/api': ''}
    }
    },
    }

    ...
    }
  • 在 devServer 中 我们配置 proxy 进行接口的代理,将我们本地地址转换为真实的服务器地址,此时我们同样能顺利的获取到数据,不同点在于接口状态变成了 304(重定向)