Home >Web Front-end >JS Tutorial >Very practical code collection for vue2.0 projects

Very practical code collection for vue2.0 projects

php中世界最好的语言
php中世界最好的语言Original
2018-03-08 09:31:322382browse

这次给大家带来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: &#39;app&#39;,    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 &#39;a.vue&#39; import a from &#39;b.vue&#39; import a from &#39;c.vue&#39; import a from &#39;main.vue&#39; let routes = [
  {   path: &#39;/login&#39;,   component: a,   name: &#39;a&#39;},{     path: &#39;/&#39;,     component: main,     name: &#39;数据中心&#39;,     iconCls: &#39;iconfont icon-shuju&#39;, //假装有个icon图标
     children: [
            { path: &#39;/main/b&#39;, component: b, name: &#39;b&#39; },
            { path: &#39;/main/c&#39;, component: c, name: &#39;c&#39; },
        ]
    },
]export default routes;//main.js 入口js文件import routes from &#39;./routes
const router = new VueRouter({
  mode: &#39;history&#39;,
  routes
})
new Vue({
  el: &#39;#app&#39;,
  template: &#39;<App/>&#39;,
  router,
  components: { App }
}).$mount(&#39;#app&#39;)

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

//menus.js  属于vuex模块export default {  &#39;0&#39;: &#39;all&#39;,  &#39;2&#39;: &#39;breast&#39;,  &#39;3&#39;: &#39;leg&#39;,  &#39;4&#39;: &#39;face&#39;,  &#39;5&#39;: &#39;others&#39;,  &#39;6&#39;: &#39;buttocks&#39;,  &#39;7&#39;: &#39;stockings&#39;}//router.js 路由文件import menus from &#39;../store/menus&#39;; //引入const getRouters = () => {  return Object.keys(menus).map(key => {    return {      path: `/${menus[key]}/:page(\\d+)?`,      component: createListView(Number(key))
    }
  })
}export default new Router({  mode: &#39;history&#39;,  routes: [
        { path: &#39;a&#39;, 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 ? (&#39;0&#39; + m) : m  var d = date.getDate()
  d = d < 10 ? (&#39;0&#39; + d) : d  var h = date.getHours()  var minute = date.getMinutes()
  minute = minute < 10 ? (&#39;0&#39; + minute) : minute  return y + &#39;-&#39; + m + &#39;-&#39; + d + &#39; &#39; + h + &#39;:&#39; + minute
}export function test (a) {   return `${a}aaaa`}
......//main.js 入口js文件import Vue from &#39;vue&#39;import * as filters from &#39;./filters&#39;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: &#39;login&#39;,                        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 = &#39;POST&#39;;//在请求之前可以进行一些预处理和配置
  // continue to next interceptor  next((response) => {//在响应之后传给then之前对response进行修改和逻辑判断。对于token时候已过期的判断,就添加在此处,页面中任何一次http请求都会先调用此处方法
     response.body = &#39;...&#39;;
    return response;
  });
});

相信看了本文案例你已经掌握了方法,更多精彩请关注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!

Statement:
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