vue实践过程之技术实现

实现项目

这个项目和微吉风很像,不过它是小程序,我这里的是webapp,哈哈。其实我这这个项目就是玩玩,为了练习练习vue而来,积累一下前端如何前后端分离,感受一下vue的美丽,拥抱一下Muse-UI。

接口设计

用flask写的接口api在做这个前端项目的时候有调整过,接口主要有:

实现

1.数据来源:模拟登陆:学校教务系统官网

2.数据简化:模拟登陆的过程是在服务器完成的,请求的到数据通过服务器进行刷选后简化数据,再返回给浏览器。几乎所有的请求都是要模拟登陆一次学校教务系统,再请求数据的,数据都是不会保存到服务器的。

3.数据更新周期:分析返回来的数据,会发现有些数据变动非常小,如果每次打开页面都向服务器发起请求,就太消耗服务器资源了。比如课表都几乎是一学期才会有变动的,频繁请求就有点多余。但是这里设计的服务器是不打算保存任何与用户相关的信息的,所以这里用到了WebStorage的储存方案,localStorage(目前主流的浏览都支持)使用localStorage来缓存这些变化不大的数据,比如课表数据,周数,个人学年时间等。

拓展:只读的localStorage 属性允许你访问一个Document 源(origin)的对象 Storage;其存储的数据能在跨浏览器会话保留。localStorage 类似 sessionStorage,但其区别在于:存储在 localStorage 的数据可以长期保留;而当页面会话结束——也就是说,当页面被关闭时,存储在 sessionStorage 的数据会被清除 。

应注意,无论数据存储在 localStorage 还是 sessionStorage它们都特定于页面的协议。

另外,localStorage 中的键值对总是以字符串的形式存储。 (需要注意, 和js对象相比, 键值对总是以字符串的形式存储意味着数值类型会自动转化为字符串类型).

语法:

//设置值
localStorage.setItem('name', 'Cendeal');
//获取值
localStorage.getItem('name');
//或者这获取值
localStorage.name
//删除值
localStorage.removeItem('name');
//或者也可以这样删除值
delete localStorage.name
// 移除所有
localStorage.clear();

下面是计算数据存活周期:

/**
 * 计算生存时间
 * @param Date now-当前时间
 * @param Number day-天数
 * @return Number
 */
function calculateExpiration(now,day) {
    let future = new Date()
    future.setHours(0,0,0,0)
    future.setDate(now.getDate()+day)
    return Math.floor(future - now)
}

/**
 * 获取当前周的生存时间
 * @return Number  生存时间-秒
 *
 */
function getCurrentWeekExpiration() {
    let now = new Date()
    return calculateExpiration(now,8-now.getDay())
}

/**
 * 获取课表的生存周期
 * @param Number totalWeek-总周数
 * @return Number 生存时间-秒
 */
function getScheduleExpiration(totalWeek=22) {
    let now = new Date()
    return calculateExpiration(now,totalWeek*7)
}

export {getCurrentWeekExpiration,getScheduleExpiration}

4.改造localStorage:了解到localStorage储存室没有生命周期的,它依赖浏览器的清除规则,一般都是需要用户手动清除数据的,那么要怎样才知道课表需要更新数据呢,除了用户自己手动更新外,还需要设置一个更新周期,明显一般都是学期末据需要更新数据了,那么就可以考虑为其设置存活时间。由于localStorage是没有这函数的,所以这里重写了一个,为localStorage添加存活时间。

方案是这样的:每次存新键值时,先计算这个数据可以存储多久,然后把时间和键值一起存进去,当取值的时候就判断当前时间是否超过了那个键值的存活时间,如果超过了就delete它,并返回null或undefinded

代码如下:

class JluzhLocalStorage {

    //获取值
    getItem(key) {
        let now = new Date()
        let data = JSON.parse(localStorage.getItem(key))
        if (data != null) {
            if (data.expiration != null) {
                let expiration = new Date(data.expiration)
                if (expiration - now <= 0) {
                    delete localStorage['key']
                    return undefined
                }
            }

            return data.val
        } else {
            return null
        }


    }

    //默认无限时间
    setItem(key, val, expiration = null) {
        let time = null
        if (expiration != null) {
            let now = new Date()
            time = now.setSeconds(now.getSeconds() + expiration)
        }
        let data = {val: val, expiration: time}
        localStorage.setItem(key, JSON.stringify(data))
    }

    //清空
    clear() {
        localStorage.clear()
    }

    //获取长度
    get length() {
        return localStorage.length
    }

    get info() {
        let data = {
            size: 0,
            count: localStorage.length,
            keys: []
        }
        let temp = 0
        for (let i in localStorage) {
            temp += 1

            if (temp > data.count) {
                break
            }
            let blob = new Blob([localStorage[i]])
            data.size += blob.size
            data.keys.push(i)

        }
        return data
    }

}

const jluzhLocalStorage = new JluzhLocalStorage()
export default jluzhLocalStorage

5.主题样式保存方案:这里主题保存样式也是利用了localStorage进行保存,服务器不会同步,清掉缓存就会恢复默认主题。sessionStorage我用来保存课表课程的颜色块数据,所以每次打开新的会话颜色都变化。

6.主题状态统一:这里使用的是vuex,通过store.js里的state保存主题的样式,更新使用mutations里面定义的函数进行更新。

代码:

import Vue from "vue"
import Vuex from "vuex"

Vue.use(Vuex)
// noinspection JSValidateTypes
const store = new Vuex.Store({
    state: {
        app_title: '吉机',
        app_host: 'http://www.cendeal.cn:5001/jlu/api',
        theme: {
            nav_style: {
                backgroundColor: 'rgb(244, 67, 54)',
                color: 'white',
                'z-index': 999
            },
            nav_active_color: 'green',

            head_pic_style: {
                backgroundColor: '#ffca28',
                'position': 'relative',
                'top': '8px'
            },
            head_text_style: {
                'color': '#7cb342'
            },
            float_btn_style: {
                'bg': 'red',
                'text': 'yellow'
            }
        },
        url_paths: {
            u_login: '/login',
            u_schedule: '/querySchedule',
            u_score: '/queryScore',
            u_week: '/getCurrentWeek',
            u_lines: '/getStuTimeLines',
            u_auth: '/auth',
            u_logout: '/logout'
        },
        jluzh_courses: '',
        current_week:1,

    },
    getters: {
        navStyle: state => {
            return state.theme.nav_style
        },
        barColor: state => {
            return state.theme.nav_style.backgroundColor
        },
        urlPaths: state => {
            return state.url_paths
        },
        headPicStyle: state => {
            return state.theme.head_pic_style
        },
        headTextStyle: state => {
            return state.theme.head_text_style
        },
        theme: state => {
            return state.theme
        }
    },
    mutations: {
        updateTheme: function (state, theme) {
            if (theme.hasOwnProperty('float_btn_bg'))
                state.theme.float_btn_style.bg = theme.float_btn_bg

            if (theme.hasOwnProperty('float_btn_text_color'))
                state.theme.float_btn_style.text = theme.float_btn_text_color

            if (theme.hasOwnProperty('nav_active_color'))
                state.theme.nav_active_color = theme.nav_active_color

            if (theme.hasOwnProperty("nav_bg"))
                state.theme.nav_style.backgroundColor = theme.nav_bg

            if (theme.hasOwnProperty('nav_text_color'))
                state.theme.nav_style.color = theme.nav_text_color

            if (theme.hasOwnProperty('head_pic_bg'))
                state.theme.head_pic_style.backgroundColor = theme.head_pic_bg

            if (theme.hasOwnProperty('head_pic_text_color'))
                state.theme.head_text_style.color = theme.head_pic_text_color
        },
        initTheme:function () {
            let theme = localStorage.getItem('jluzh_theme')
            if(theme != null || theme != undefined){
                store.commit('updateTheme',JSON.parse(theme))
            }
        },
        updateWeek:function (state,week) {
            state.current_week = week
        },
        updateCourses:function (state,courses) {
            if(courses==null)
            delete localStorage['jluzh_courses']
            state.jluzh_courses = courses
        }
    },
    actions: {}
})
export default store

7.跨域问题:因为后端和前端部署不是在同一个域下的,后端是通过gunicorn部署在5001端口,前端直接使用的nginx监听的80端口,所以当前端发起数据请求时就会出现跨域,请求会被浏览器拦截。为了解决这个问题。这里使用的是vue-jsonp发起跨域请求(其原理就是js文件的请求是可以跨域的)【这里处理的不是太好,还是存在一点问题,其实比较简单的就是采用代理的方法】

/**
 * created by cendeal 2019/3/7
 * 通过vue-jsonp 进行跨域请求数据
 * 所有函数返回的都是promise对象
 * 要求:全局使用vue-jsonp,vuex
 */

// 登陆
function loginjs(token) {
    return this.$jsonp(this.$store.state.app_host + this.$store.getters.urlPaths.u_auth, {
        token: token,
        callbackName: 'jsonpCallback'
    })

}


// 获取选项
function getSelection() {
    return this.$jsonp(this.$store.state.app_host + this.$store.getters.urlPaths.u_lines,
        {callbackName: 'jsonpCallback'})
}

// 获取分数
function getScore(grade, term) {
    return this.$jsonp(this.$store.state.app_host + this.$store.getters.urlPaths.u_score,
        {
            Grade: grade,
            term: term,
            callbackName: 'jsonpCallback'
        })
}

// 获取课表
function getScheduleJs(Grade = null, term = null) {
    let data = {Grade: '0', term: '0', callbackName: 'jsonpCallback'}
    if (Grade != null && term != null) {
        data.Grade = Grade
        data.term = term
    }
    return this.$jsonp(this.$store.state.app_host + this.$store.getters.urlPaths.u_schedule, data)
}

// 获取当前周
function getCurrentWeek() {
    let data = {callbackName: 'jsonpCallback'}
    return this.$jsonp(this.$store.state.app_host + this.$store.getters.urlPaths.u_week, data)
}


export {loginjs,getSelection,getScore,getScheduleJs,getCurrentWeek}

8.课表页面实现:这里使用了另外的swiper不是muse-ui的,因为muse-ui的swiper实现不了想要的效果。就在好友的建议下使用了另外的vue-awesome-swiper它是基于swiper4的。比较难受的就是,我一开始就打算用它的loop属性,但是添加上去的时候就出错了,网上也很少相关的内容,就先放弃了loop属性。就选择直接生成21张的课表的swiper-slide,在朋友的iphone 浏览器打开居然卡了,没办法就必须优化,然后在尝试和看swiper4的文档,后来发现可以先不让swiper进行init,先让它的params的loop的值初始为true后再调用init,结果成功了,然后swiper-slide的数量可以减到3了。【如果我不执着与想要swiper的cude立体转换效果,根本就不用这么麻烦,1个swiper-slide就可以,也不用用到loop】

代码:Schedule.vue

9.最后是学习笔记。

0_1.png
0_2.png
0_3.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,919评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,567评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,316评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,294评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,318评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,245评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,120评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,964评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,376评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,592评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,764评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,460评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,070评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,697评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,846评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,819评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,665评论 2 354