Very practical code collection for vue2.0 projects

php中世界最好的语言
Release: 2018-03-08 09:31:32
Original
2270 people have browsed it

这次给大家带来vue2.0的项目非常实用的代码集合,在项目中使用vue2.0的代码注意事项有哪些,下面就是实战案例,一起来看一下。

1、全局增加进度条提示
nprogress地址

// main.js 入口js文件 import VueRouter from 'vue-router' import NProgress from 'nprogress'Vue.use(VueRouter); //注册路由插件NProgress.configure({ showSpinner: false }); //进度条配置router.beforeEach((to, from, next) => { NProgress.start(); }) router.afterEach(transition => { NProgress.done(); });
Copy after login

2、路由拦截

router.beforeEach((to, from, next) => {//假设登陆成功后,user信息保存在sessionStorage中。 if (to.path == '/login') { sessionStorage.removeItem('user'); //如果访问登录页,清空之前sessionStorage中的user信息 } let user = JSON.parse(sessionStorage.getItem('user')); if (!user && to.path != '/login') { next({ path: '/login' }) } else { next() }//如果访问非登陆页,判断是否有保存的user信息,如果没有,则判断为非法访问,重定向到登录页面})
Copy after login

3、路由切换动效

Copy after login

4、路由嵌套

//router.jsimport a from 'a.vue' import a from 'b.vue' import a from 'c.vue' import a from 'main.vue' let routes = [ { path: '/login', component: a, name: 'a'},{ path: '/', component: main, name: '数据中心', iconCls: 'iconfont icon-shuju', //假装有个icon图标 children: [ { path: '/main/b', component: b, name: 'b' }, { path: '/main/c', component: c, name: 'c' }, ] }, ]export default routes;//main.js 入口js文件import routes from './routes const router = new VueRouter({ mode: 'history', routes }) new Vue({ el: '#app', template: '', router, components: { App } }).$mount('#app')
Copy after login

ps:路由的配置,启动,挂载可以分别放在不同的页面。将模块化进行到底。routes对象,甚至可以来自于vuex,便于管理数据。如下例子:

//menus.js 属于vuex模块export default { '0': 'all', '2': 'breast', '3': 'leg', '4': 'face', '5': 'others', '6': 'buttocks', '7': 'stockings'}//router.js 路由文件import menus from '../store/menus'; //引入const getRouters = () => { return Object.keys(menus).map(key => { return { path: `/${menus[key]}/:page(\\d+)?`, component: createListView(Number(key)) } }) }export default new Router({ mode: 'history', routes: [ { path: 'a', component: a }, ...getRouters() ] })
Copy after login

5、全局过滤器
一个项目中,可能要用到很多过滤器来处理数据,多个组件公用的,可以注册全局过滤器。单个组件使用的,就挂载到实例filters中。
项目做的多了以后,可以整理一套常用的filters,不用反复的写。比如:时间等各种操作,数据格式转化,单位换算,部分数据的md5加密等...

//filters.js 过滤器文件export function formatDateTime (date) { //格式化时间戳 var y = date.getFullYear() var m = date.getMonth() + 1 m = m < 10 ? ('0' + m) : m var d = date.getDate() d = d < 10 ? ('0' + d) : d var h = date.getHours() var minute = date.getMinutes() minute = minute < 10 ? ('0' + minute) : minute return y + '-' + m + '-' + d + ' ' + h + ':' + minute }export function test (a) { return `${a}aaaa`} ......//main.js 入口js文件import Vue from 'vue'import * as filters from './filters'Object.keys(filters).forEach(key => { Vue.filter(key, filters[key]) })
Copy after login

6、http拦截器
拦截器是全局的,拦截器可以在请求发送前和发送请求后做一些处理。
拦截器在一些场景下会非常有用,比如请求发送前在headers中设置access_token,或者在请求失败时,提供通用的处理方式。

axios实现-axios全攻略

// http request 拦截器axios.interceptors.request.use( config => { if (store.state.token) { // 判断是否存在token,如果存在的话,则每个http header都加上token config.headers.Authorization = `token ${store.state.token}`; } return config; }, err => { return Promise.reject(err); });// http response 拦截器axios.interceptors.response.use( response => { return response; }, error => { if (error.response) { switch (error.response.status) { case 401: // 返回 401 清除token信息并跳转到登录页面 store.commit(types.LOGOUT); router.replace({ path: 'login', query: {redirect: router.currentRoute.fullPath} }) } } return Promise.reject(error.response.data) // 返回接口返回的错误信息 });
Copy after login

vue-resource实现-vue-resource全攻略

Vue.http.interceptors.push((request, next) => {  console.log(this)//此处this为请求所在页面的Vue实例 // modify request request.method = 'POST';//在请求之前可以进行一些预处理和配置 // continue to next interceptor  next((response) => {//在响应之后传给then之前对response进行修改和逻辑判断。对于token时候已过期的判断,就添加在此处,页面中任何一次http请求都会先调用此处方法  response.body = '...';     return response; }); });
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

相关阅读:

不同版本的vscdoe如何调试不同版本nodejs

Vue.js的2.0后台系统实战案例

The above is the detailed content of Very practical code collection for vue2.0 projects. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!