0%

去哪儿网踩坑(Vue-cli配置和Vuex)

去哪儿网项目链接

Vue-cli 配置

Vue-cli 2.x 和 Vue-cli 3.x 配置webpack别名目录 alias

vue-cli 2.x

1
2
3
4
5
6
7
8
9
10
11
module.exports = {
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
// resolve 函数文件已配置好
'styles': resolve('src/assets/styles')
}
}
}

vue-cli 3.x

直接在项目根目录新建 vue.config.js

1
2
3
4
5
6
7
8
9
10
11
12
const path = require('path')

module.exports = {
configureWebpack: {
resolve: {
alias: {
'styles': path.resolve('src/assets/styles')
}
}
}
}

stylus配置别名

在以上配置webpack别名目录后,在页面引入 stylus 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
...
</template>

<script>
...
</script>

<style lang="stylus" scoped>
/* 此处的~styles 指的就是 src/assets/styles */
@import '~styles/varibles.styl';
...
</style>

keep-alive

http持久链接 keep-alive 维基百科

Vue官方解释

keep-alive 是持久化连接技术

但在vue中是包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们,当组件在 <keep-alive> 内被切换,它的 activateddeactivated 这两个生命周期钩子函数将会被对应执行。由于不会销毁,所以生命周期函数 createdmounted都不会执行第二次

Vuex

普通情况下 store 就已够用,但如果数据特别大而且特别多的时候,而且还是相互之间需要传值,这个时候就该 vuex 上场了。

官方解释:

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式

state

相当于组件中的 data,只要挂载到Vue上,所有组件都可以访问

组件中获取state

第一种 简单直接,就是写起来有点麻烦

1
2
3
4
5
<template>
<div>
{{this.$store.state.city}}
</div>
</template>

第二种 对象展开运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<div>
{{city}}
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState(['city'])
}
}
</script>

getters

actions

优势

  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。
1
2
3
4
5
actions: {
changeCity(context, city) {
context.commit('changeCityName', city)
}
}

组件中调用 dispath 可以调用到actions内的函数

1
this.$store.dispatch('changeCity', '北京')

mutations

1
2
3
changeCityName(state, city) {
state.city = city
}

module

异步加载组件

将原来的

1
2
3
4
5
6
7
import Home from './page/home/Home.vue'

export default new Router({
routes: [
{ path: '/', component: Home }
]
})

修改为异步加载,有效减少的 app.js 文件大小

1
2
3
4
5
6
7
import Home from './page/home/Home.vue'

export default new Router({
routes: [
{ path: '/', component: () => import('./page/home/Home.vue') },
]
})