Vue, App与我(十)

Vue, App与我(十)

前言:订单页面

  • Big-man最近在书写一个天天特惠的案例,所以对于订单的处理开始有了一些看法和想法,由于管理App的仅仅只有Big-man一个人,所以后台的实现逻辑、前端的页面展现以及将两者相结合的方法和方式都是Big-man在进行测试和维护的。所以Big-man觉得应该把他处理这一功能的问题、解决办法以及思路分享到自己的博客上。

前端展现:

产品列表:

  • Big-man所接触的项目和观察、统计别人写的项目都可以得出在订单展示的页面之前都会存在一个页面那就是产品的列表展示页面,而Big-man所需要实现的产品列表页面也就是跟所谓的产品列表页面类似的效果。

  • 在用户点击进入产品列表页面的时候,Big-man觉得需要进行一个判断,大家估计也可以想到的,也就是判断用户是否是登录的用户,因为产品的交易需要用户的信息,没有进行登录就允许处理的话,会带来许多的安全隐患,所以在这里我们需要对用户进行验证。代码如下:

产品详情:(逻辑代码)

  • 代码:
<script>
import Store from '../../store.js'
export default {
    mounted() {
        if(Store.getAuthUid()) {
            this.$http.get(this.whoami, {}).then((response) =>{
                const ret = JSON.parse(response.data)
                if(ret && ret['code'] === 0) {
                    this.username = ret['nickname'] ? ret['nickname'] : ret['username']
                }
            })
        }
        const id = +(this.$route.params.id)
        if(!id) {
            this.isError = true
            this.error = '参数错误'
        } else {
            this.isLoading = true
            this.getData(() => window.scrollTp(0, 0))
        }
        this.getWx()
        this.getCommentData()
    },
}
</script>
  • store.js
export default {
  AUTH_UID: 'authuid',
  INDEX_SAVE: 'index',
  USERNAME:'username',
  COMPANYID:'companyid',
  POINT:'point',
  INTOPAGE:'intopage',
  VERSION:'version',
  getAuthUid: function(){
    return localStorage.getItem(this.AUTH_UID) || ""//|| 'UjAECwFXAlJWB1oGDwwHXVRXBV8EUQFXBAdQWgwDWQsCVQ'
  },
  setAuthIid: function(authuid){
    localStorage.setItem(this.AUTH_UID,authuid)
  },

  getIndex: function(){
    return JSON.parse(localStorage.getItem(this.INDEX_SAVE))
  },
  setIndex: function( data ){
    var str = data;
    if( typeof data === 'object' ){
      str = JSON.stringify(data)
    }
    return localStorage.setItem(this.INDEX_SAVE,str)
  },

  setPOINT: function(point){
    var str = point;
    if(typeof point === 'object'){
       str = JSON.stringify(point);
    }
    return localStorage.setItem(this.POINT,str)
  },

  getPOINT: function(){
     try{
       return JSON.parse(localStorage.getItem(this.POINT))
      }catch(e){
        console.log(e.toLocaleString())
     }
  },

  getUserName: function(){
    return localStorage.getItem(this.USERNAME) || ""
  },
  setUserName: function(username){
    localStorage.setItem(this.USERNAME,username)
  },

  getCompanyid: function(){
    return localStorage.getItem(this.COMPANYID) || ""
  },
  setCompanyid: function(companyid){
    localStorage.setItem(this.COMPANYID,companyid)
  },
  getIntoPage: function(){
    return localStorage.getItem(this.INTOPAGE) || ""
  },
  setIntoPage: function(intopage){
    localStorage.setItem(this.INTOPAGE,intopage)
  },
  getVersion: function(){
    return localStorage.getItem(this.VERSION) || ""
  },
  setVersion: function(version){
    localStorage.setItem(this.VERSION,version)
  }
}
  • Store.getAuthUid();
  • 方法在上面的方法中已经书写得很明白了,就是localStorage.getItem()方法当中的参数:
this.getAuthId||""||'UjAECwFXAlJWB1oGDwwHXVRXBV8EUQFXBAdQWgwDWQsCVQ'
  • 那大家可能又会继续问Big-man了?那什么是this.getAuthId了?下面Big-man带大家去看另外一个文件main.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource'
import Calendar from 'vue2-datepick'
import Config from './config.js'
import Store from './store.js'

import './assets/css/common.css'
import 'mint-ui/lib/style.css'


import FastClick from 'fastclick'
if ('addEventListener' in document) {
    document.addEventListener('DOMContentLoaded', function() {
        FastClick.attach(document.body);
    }, false);
}
import { InfiniteScroll,Swipe, SwipeItem, Loadmore } from 'mint-ui';

Vue.use(VueRouter)
Vue.use(VueResource)
Vue.use(Calendar)

Vue.use(InfiniteScroll)
Vue.component(Swipe.name,Swipe)
Vue.component(SwipeItem.name,SwipeItem)
Vue.component(Loadmore.name,Loadmore)

Vue.http.options.root = Config.api

import routes from './routes.js'
const router = new VueRouter({
  // mode: 'history',
  hashbang: false,
  history: true,
  linkActiveClass: 'active',
  routes: routes
})

Vue.http.interceptors.push((request, next) => {

  // modify request
  if(Store.getAuthUid()){
    Vue.http.headers.common['Authorization'] = 'Xyapp ' + Store.getAuthUid()
  }
  // continue to next interceptor
  next();
});
function receiveMessage(event){
  const data = JSON.parse(event.data);
  if(data['lat'] && data['lng']){
     Store.setPOINT(data);
  }
}
window.document.addEventListener("message", receiveMessage, false);

router.beforeEach( (to,from,next) => {
  next();
});

new Vue({
  router,
  template : '<div id="app"><router-view class="view"></router-view></div>',
}).$mount('#app')
  • Vue.http.interceptors.push((request, next) => { function()})方法的分析;
  • 相信很多接触这个方法的使用都是比较陌生的,但是这却是一个很重要的、很实用的方法——vue-resource拦截器使用;

  • 在vue项目中使用vue-resource的过程中, 临时增加了一个需求,需要在任何一个页面以及任何一次http请求,增加对token过期的判断,如果token已过期,需要跳转至登录页面。如果要在每个页面中的http请求操作中添加一次判断,那么会是一个非常大的修改工作量。那么,vue-resouce是否存在一个对于任何一次请求响应捕获的公共回调函数呢?答案是肯定有的!

  • vue-resourceinterceptors拦截器的作用正是解决此需求的妙方。在每次http的请求响应之后,如果设置了拦截器如下,会优先执行拦截器函数,获取响应体,然后才会决定是否把response返回给then进行接收。那么我们可以在这个拦截器里边添加对响应状态码的判断,来决定是跳转到登录页面还是留在当前页面继续获取数据。

  • Example 1:

下边代码添加在main.js中
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;

  });
});
  • 在见证此方法之前,Big-man在网上搜寻到了另外一个方法,也能在一定程度上降低修改工作量。方法是为Vue绑定一个this.$$http.get方法取代this.$http.get方法,每个页面的http请求添加个$$http前即可。大神代码如下:
// ajax.js
function plugin(Vue){
    Object.defineProperties(Vue.prototype,{
        $$http:{
            get(){
                return option(Vue);
            }
        }
    })
}
function option(Vue){
    let v = new Vue();
    return {
        get(a,b){
            let promise = new Promise(function(reslove,reject){
                v.$http.get(a,b).then((res)=>{
                    reslove(res)
                },(err)=>{
            //处理token过期问题。
                })
            })
            return promise;
        }
    }
}
module.exports=plugin;


//main.js

import ajax from './ajax.js'
Vue.use(ajax)

  • Vue.http.headers.common['Authorization'] = 'Xyapp ' + Store.getAuthUid()分析;可能有存在不理解此方法的朋友们。

JackDan9 Thinking

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值