单页应用的基本配置
路由配置
由于 Vue 这类框架都是以一个或多个单页构成,在单页内部跳转并不会重新渲染 HTML 文件,其路由可以由前端进行控制。
javascript
/* 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模式 - 页面组件没有进行按需加载
下面是我们优化结束的代码:
javascript
/* router.js */
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
let base = `${process.env.BASE_URL}` // 动态获取二级目录
export default new Router({
mode: 'history',
base: base,
routes: [{
path: '/',
name: 'home',
component: () => import('./views/Home.vue')
}, {
path: '/about',
name: 'about',
component: () => import('./views/about.vue')
}]
})改为 history 后 url 的路径就变成了 http://127.0.0.1:8080/vue/about,而不是原来的 http://127.0.0.1:8080/vue/#/about,但是需要注意页面渲染 404 的问题,具体可查阅:HTML5 History 模式
Vuex 配置
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式
javascript
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
}
})如果是中大型项目,使用 Vuex 来管理错综复杂的状态数据是很有帮助的,而为了后期的拓展性和可维护性,这里不建议使用 CLI 生成的一份配置文件来管理所有的状态操作,可以把它拆分为以下目录:
bash
└── store
├── index.js # 组装模块并导出 store 的地方
├── actions.js # 根级别的 action
├── mutations.js # 根级别的 mutation
└── modules
├── moduleA.js # A模块
└── moduleB.js # B模块按模块进行了划分,每个模块中都可以包含自己 4 个核心功能。比如模块 A 中:
javascript
/* 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 模块,并在 index.js 中引入:
javascript
/* 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
}
}
})这样项目中状态的模块划分就更加清晰,对应模块的状态只需要修改相应模块文件即可。详细的案例代码可参考文末 github 地址
公共设施配置
项目开发中肯定需要对公共的方法进行封装使用,可以在 src 目录下建一个 common 文件夹来存放其配置文件:
code
└── src
└── common
├── index.js # 公共配置入口
├── validate.js # 表单验证配置
└── other.js # 其他配置在入口文件中可以向外暴露其他功能配置的模块,比如:
javascript
/* index.js */
import Validate from './validate'
import Other from './other'
export {
Validate,
Other,
}这样在页面中只需要引入一个 index.js 即可。本案例代码地址:single-page-project