vue项目搭建、router配置、vuex配置

时间:2020-04-16 19:36:53   收藏:0   阅读:69
  1. 安装router
npm i vue-router --save-dev
  1. 配置router
src
  - router
    - index.js
// 1. 引入vue和vue-router
import Vue from ‘vue‘
import Router from ‘vue-router‘
// 模块路由可以写在其他的文件夹下,在index.js中引入即可
import routes from ‘./modules/routes‘
// 2. 在vue中使用router
Vue.use(Router)

// 3. 创建一个router
const router = new Router ({
  mode: ‘history‘,
  routes
})

// 4. 导航前置守卫与导航后置守卫
// 设置路由导航前置守卫,进入路由前的操作
router.beforeEach((to, from, next) => {
  // to: 即将前往的页面路由
  // from: 即将离开的页面路由
  // next: 必须含有,进行页面跳转
  console.log(to, from, next)
  // 在这里面可以进行路由菜单的获取
})

// 导航后置守卫,进入路由后的操作
router.afterEach(() => {
  // loadingInstance.close()
})

// 5. 将路由导出即可
export default router

第三步:状态管理(vuex)的安装与配置

  1. 安装vuex
npm i vuex --save-dev
  1. vuex的介绍
state: {
  name: ‘zhangsan‘,
  age: 18
}
getters: {
  age: state => {
    return state.age + 2 // 20 
  }
}
// 但是在一般使用中吧getters都可以放到一个文件中,这样在使用数据的时候能够更加明了,下面再进行介绍
mutations: {
  SET_NAME: (state, name) => {
    state.name = name
  }
}
actions: {
  SetName ({ commit }, name) {
    commit(‘SET_NAME‘, name)
  }
}
const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: { ... },
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

vuex的具体配置

store
  - modules
    - app.js
  - getters.js
  - index.js
// app.js
const app = {
  namespace: true,  // 命名空间
  state: {
    name: ‘zhangsan‘,
    age: 18
  },
  mutations: {
    SET_NAME: (state, name) => {
      state.name = name
    }
  },
  actions: {
    SetName ({ commit }, name) {
      commit(‘SET_NAME‘, name)
    }
  }
}

export default app
// getters.js
const getters = {
  name: state => state.app.name
}

export default getters

// index.js
import Vue from ‘vue‘
import Vuex from ‘vuex‘
import app from ‘./modules/app‘
import getters from ‘./getters‘
Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    app
  },
  getters
})

export default store

main.js中引入

import router from ‘@/router‘
import store from ‘@/store‘

new Vue({
  el: ‘#app‘,
  router,
  store,
  components: { App },
  template: ‘<App/>‘
})
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!