这次给大家带来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!

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.


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

WebStorm Mac version
Useful JavaScript development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
