Vue小项目总结

前几天,跟着教程写了一个 Vue 的仿新闻端的小项目。

项目结构

vue init webpack-simple xxx 构建项目,内部的主要结构

1
2
3
4
5
6
7
8
9
10
11
12
————根目录
—— src //主要的代码
—— assets //静态文件,css,js,img
—— components //组件
—— filters //过滤器
—— store //Vuex
—— App.vue //页面级的Vue
—— main.js //实例化Vue及全局引入一些东西
—— router.config.js //路由配置
—— webpack.config.js //webpack配置
—— index.html //输出
—— …… //webpack的一些东西

axios

由于 vue-resource 停更了,axios 是用来做交互的不二选择,而且 axiosPromise 版的,紧跟潮流。

由于 axios 中没有 install 方法,所以不能直接用 Vue.use() ,以为不在每一个需要发送请求的组件中都引用一次 axios ,可以将它写进 Vue 的原型链中

1
Vue.prototype.$http = axios;

这样子,在 Vue 实例的组件中,需要进行交互的时候,就可以这样用

1
this.$http.xxx( )

axios 提供了接口允许在发送请求前和接收响应前进行操作

1
2
3
4
5
6
7
8
9
10
11
12
13
axios.interceptors.request.use((config) => {
//…… 请求发送前可以在这里进行一些操作
return config;
}, err => {
return Promise.reject(err);
})
axions.interceptors.response.use((response) => {
//…… 响应接收前可以在这里进行一些操作
return response
}, ,err => {
return Promise.reject(err);
})

Vuex

关于某些组件中状态,用 Vuex 来管理是最合理的,它有 install 方法,可以使用 Vue.use(Vuex)

1
2
3
4
5
6
7
8
9
10
11
12
13
import Vue from 'vue'
import Vuex from 'vuex'
import actions from './actions'
import mutations from './mutations'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
mutations
},
actions
})

然后将其主要流程

1
dispatch -> actions -> mutations -> state -> components

组件中发起状态变化的消息,actions 接收到变化,传递给 mutations 处理 state 的值,然后 componentsgetters 获取 state ,这样就实现了状态的变化

在组件中获取 states

1
2
3
import mapGetters from 'vuex'
mapGetters(["xxx", "xxx"])

watch 属性

vue 里有个属性,watch,可以监听路由的变化

1
2
3
4
5
6
watch:{
$route(to, from){
//to.path 是跳转后的路由
//from.path 是当前页面是从哪里跳转过来的
}
}

Vue-router

使用路由是单页面应用不可或缺的一部分,同时也是要配置路由的 config

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import VueRouter from 'vue-router'
import routes from './route.config'
Vue.use(VueRouter)
const router = new VueRouter({
mode: 'history', //一种加载模式
scrollBehavior: () => {
{
x: 0,
y: 0
}
}, //滚动条的滚动行为
routes //加入路由配置
})
new Vue({
router
})

先是引入 VueRouter 和路由的配置,然后实例化路由,最后将实例化的路由挂在 Vue

使用

1
2
3
<router-link to='/xxx'></router-link>
<router-view></router-view>

在拼接路由,即需要传参时

1
2
3
4
5
6
7
8
9
10
<!-- 拼接路由时 -->
<router-link :to="'/xxx/' + id"> </router-link>
//router.config
{
path: '/xxx/:id',
component: 'xxx'
}

这样写,在跳转到该路由绑定的 component 时,就可以附带上参数 id

this.$route.params 即可获取当前路由中附带的参数,然后就可以在 mounted 做点东西了