Very practical code collection for vue2.0 projects
这次给大家带来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(); });
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信息,如果没有,则判断为非法访问,重定向到登录页面})
3、路由切换动效
<!--app.vue 根组件--><template> <div id="app"> <transition name="fade" mode="out-in"> <router-view></router-view> </transition> </div></template><script> export default { name: 'app', components: {} }</script><style> .fade-enter-active,.fade-leave-active { transition: opacity .2s ease; } .fade-enter,.fade-leave-active { opacity: 0; }</style>
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: '<App/>', router, components: { App } }).$mount('#app')
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() ] })
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]) })
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) // 返回接口返回的错误信息 });
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; }); });
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
相关阅读:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Some users encountered errors when installing the device, prompting error code 28. In fact, this is mainly due to the driver. We only need to solve the problem of win7 driver code 28. Let’s take a look at what should be done. Do it. What to do with win7 driver code 28: First, we need to click on the start menu in the lower left corner of the screen. Then, find and click the "Control Panel" option in the pop-up menu. This option is usually located at or near the bottom of the menu. After clicking, the system will automatically open the control panel interface. In the control panel, we can perform various system settings and management operations. This is the first step in the nostalgia cleaning level, I hope it helps. Then we need to proceed and enter the system and

What to do with blue screen code 0x0000001? The blue screen error is a warning mechanism when there is a problem with the computer system or hardware. Code 0x0000001 usually indicates a hardware or driver failure. When users suddenly encounter a blue screen error while using their computer, they may feel panicked and at a loss. Fortunately, most blue screen errors can be troubleshooted and dealt with with a few simple steps. This article will introduce readers to some methods to solve the blue screen error code 0x0000001. First, when encountering a blue screen error, we can try to restart

Solve the "error:expectedinitializerbefore'datatype'" problem in C++ code. In C++ programming, sometimes we encounter some compilation errors when writing code. One of the common errors is "error:expectedinitializerbefore'datatype'". This error usually occurs in a variable declaration or function definition and may cause the program to fail to compile correctly or

The win10 system is a very excellent high-intelligence system. Its powerful intelligence can bring the best user experience to users. Under normal circumstances, users’ win10 system computers will not have any problems! However, it is inevitable that various faults will occur in excellent computers. Recently, friends have been reporting that their win10 systems have encountered frequent blue screens! Today, the editor will bring you solutions to different codes that cause frequent blue screens in Windows 10 computers. Let’s take a look. Solutions to frequent computer blue screens with different codes each time: causes of various fault codes and solution suggestions 1. Cause of 0×000000116 fault: It should be that the graphics card driver is incompatible. Solution: It is recommended to replace the original manufacturer's driver. 2,

Termination Code 0xc000007b While using your computer, you sometimes encounter various problems and error codes. Among them, the termination code is the most disturbing, especially the termination code 0xc000007b. This code indicates that an application cannot start properly, causing inconvenience to the user. First, let’s understand the meaning of termination code 0xc000007b. This code is a Windows operating system error code that usually occurs when a 32-bit application tries to run on a 64-bit operating system. It means it should

If you need to program any device remotely, this article will help you. We will share the top GE universal remote codes for programming any device. What is a GE remote control? GEUniversalRemote is a remote control that can be used to control multiple devices such as smart TVs, LG, Vizio, Sony, Blu-ray, DVD, DVR, Roku, AppleTV, streaming media players and more. GEUniversal remote controls come in various models with different features and functions. GEUniversalRemote can control up to four devices. Top Universal Remote Codes to Program on Any Device GE remotes come with a set of codes that allow them to work with different devices. you may

Blue screen is a problem we often encounter when using the system. Depending on the error code, there will be many different reasons and solutions. For example, when we encounter the problem of stop: 0x0000007f, it may be a hardware or software error. Let’s follow the editor to find out the solution. 0x000000c5 blue screen code reason: Answer: The memory, CPU, and graphics card are suddenly overclocked, or the software is running incorrectly. Solution 1: 1. Keep pressing F8 to enter when booting, select safe mode, and press Enter to enter. 2. After entering safe mode, press win+r to open the run window, enter cmd, and press Enter. 3. In the command prompt window, enter "chkdsk /f /r", press Enter, and then press the y key. 4.

Quickly get started with Python drawing: code example for drawing Bingdundun Python is an easy-to-learn and powerful programming language. By using Python's drawing library, we can easily realize various drawing needs. In this article, we will use Python's drawing library matplotlib to draw a simple graph of ice. Bingdundun is a cute panda who is very popular among children. First, we need to install the matplotlib library. You can do this by running in the terminal
