vue项目前端知识点整理

微信受权后还能经过浏览器返回键回到受权页

在导航守卫中能够在next({})中设置replace: true来重定向到改路由,跟router.replace()相同javascript

router.beforeEach((to, from, next) => { if (getToken()) { ... } else { // 储存进来的地址,供受权后跳回 setUrl(to.fullPath) next({ path: '/author', replace: true }) } })

路由切换时页面不会自动回到顶部

const router = new VueRouter({ routes: [...], scrollBehavior (to, from, savedPosition) { return new Promise((resolve, reject) => { setTimeout(() => { resolve({ x: 0, y: 0 }) }, 0) }) } })

ios系统在微信浏览器input失去焦点后页面不会自动回弹

初始的解决方案是input上绑定onblur事件,缺点是要绑定屡次,且有的input存在于第三方组件中,没法绑定事件。
后来的解决方案是全局绑定focusin事件,由于focusin事件能够冒泡,被最外层的body捕获。php

util.wxNoScroll = function() { let myFunction let isWXAndIos = isWeiXinAndIos() if (isWXAndIos) { document.body.addEventListener('focusin', () => { clearTimeout(myFunction) }) document.body.addEventListener('focusout', () => { clearTimeout(myFunction) myFunction = setTimeout(function() { window.scrollTo({top: 0, left: 0, behavior: 'smooth'}) }, 200) }) } function isWeiXinAndIos () { let ua = '' + window.navigator.userAgent.toLowerCase() let isWeixin = /MicroMessenger/i.test(ua) let isIos = /\(i[^;]+;( U;)? CPU.+Mac OS X/i.test(ua) return isWeixin && isIos } }

在子组件中修改父组件传递的值时会报错

vue中的props是单向绑定的,但若是props的类型为数组或者对象时,在子组件内部改变props的值控制台不会警告。由于数组或对象是地址引用,但官方不建议在子组件内改变父组件的值,这违反了vue中props单向绑定的思想。因此须要在改变props值的时候使用$emit,更简单的方法是使用.sync修饰符。vue

// 在子组件中 this.$emit('update:title', newTitle) //在父组件中 <text-document :title.sync="doc.title"></text-document>

使用微信JS-SDK上传图片接口的处理

首先调用wx.chooseImage(),引导用户拍照或从手机相册中选图。成功会拿到图片的localId,再调用wx.uploadImage()将本地图片暂存到微信服务器上并返回图片的服务器端ID,再请求后端的上传接口最后拿到图片的服务器地址。java

chooseImage(photoMustTake) {
    return new Promise(resolve => { var sourceType = (photoMustTake && photoMustTake == 1) ? ['camera'] : ['album', 'camera'] wx.chooseImage({ count: 1, // 默认9 sizeType: ['original', 'compressed'], // 能够指定是原图仍是压缩图,默认两者都有 sourceType: sourceType, // 能够指定来源是相册仍是相机,默认两者都有 success: function (res) { // 返回选定照片的本地ID列表,localId能够做为img标签的src属性显示图片 wx.uploadImage({ localId: res.localIds[0], isShowProgressTips: 1, success: function (upRes) { const formdata={mediaId:upRes.serverId} uploadImageByWx(qs.stringify(formdata)).then(osRes => { resolve(osRes.data) }) }, fail: function (res) { // alert(JSON.stringify(res)); } }); } }); }) }

聊天室断线重连的处理

因为后端设置了自动断线时间,因此须要socket断线自动重连。
data以下几个属性,beginTime表示当前的真实时间,用于和服务器时间同步,openTime表示socket建立时间,主要用于分页,以及重连时的判断,reconnection表示是否断线重连。ios

data() { return { reconnection: false, beginTime: null, openTime: null } }

初始化socket链接时,将openTime赋值为当前本地时间,socket链接成功后,将beginTime赋值为服务器返回的当前时间,再设置一个定时器,保持时间与服务器一致。vuex

发送消息时,当有多个用户,每一个用户的系统本地时间不一样,会致使消息的顺序错乱。因此须要发送beginTime参数用于记录用户发送的时间,而每一个用户的beginTime都是与服务器时间同步的,能够解决这个问题。
聊天室须要分页,而不一样的时刻分页的数据不一样,例如当前时刻有10条消息,而下个时刻又新增了2条数据,因此请求分页数据时,传递openTime参数,表明以建立socket的时间做为查询基准。typescript

// 建立socket createSocket() { _that.openTime = new Date().getTime() // 记录socket 建立时间 _that.socket = new WebSocket(...) } // socket链接成功 返回状态 COMMAND_LOGIN_RESP(data) { if(10007 == data.code) { // 登录成功 this.page.beginTime = data.user.updateTime // 登陆时间 this.timeClock() } } // 更新登陆时间的时钟 timeClock() { this.timer = setInterval(() => { this.page.beginTime = this.page.beginTime + 1000 }, 1000) }

当socket断开时,判断beginTime与当前时间是否超过60秒,若是没超过说明为非正常断开链接不作处理。segmentfault

_that.socket.onerror = evt => { if (!_that.page.beginTime) { _that.$vux.toast.text('网络忙,请稍后重试') return false } // 不重连 if (this.noConnection == true) { return false } // socket断线重连 var date = new Date().getTime() // 判断断线时间是否超过60秒 if (date - _that.openTime > 60000) { _that.reconnection = true _that.createSocket() } }

发送音频时第一次受权问题

发送音频时,第一次点击会弹框提示受权,无论点击容许仍是拒绝都会执行wx.startRecord(),这样再次调用录音就会出现问题(由于上一个录音没有结束), 因为录音方法是由touchstart事件触发的,能够使用touchcancel事件捕获弹出提示受权的状态。后端

_that.$refs.btnVoice.addEventListener("touchcancel" ,function(event) { event.preventDefault() // 手动触发 touchend _that.voice.isUpload = false _that.voice.voiceText = '按住 说话' _that.voice.touchStart = false _that.stopRecord() })

组件销毁时,没有清空定时器

在组件实例被销毁后,setInterval()还会继续执行,须要手动清除,不然会占用内存。数组

mounted(){
    this.timer = (() => { ... }, 1000) }, //最后在beforeDestroy()生命周期内清除定时器 beforeDestroy() { clearInterval(this.timer) this.timer = null }

watch监听对象的变化

watch: {
    chatList: {
        deep: true, // 监听对象的变化 handler: function (newVal,oldVal){ ... } } }

后台管理系统模板问题

因为后台管理系统增长了菜单权限,路由是根据菜单权限动态生成的,当只有一个菜单的权限时,会致使这个菜单可能不显示,参看模板的源码:

<router-link v-if="hasOneShowingChildren(item.children) && !item.children[0].children&&!item.alwaysShow" :to="resolvePath(item.children[0].path)"> <el-menu-item :index="resolvePath(item.children[0].path)" :class="{'submenu-title-noDropdown':!isNest}"> <svg-icon v-if="item.children[0].meta&&item.children[0].meta.icon" :icon-class="item.children[0].meta.icon"></svg-icon> <span v-if="item.children[0].meta&&item.children[0].meta.title" slot="title">{{generateTitle(item.children[0].meta.title)}}</span> </el-menu-item> </router-link> <el-submenu v-else :index="item.name||item.path"> <template slot="title"> <svg-icon v-if="item.meta&&item.meta.icon" :icon-class="item.meta.icon"></svg-icon> <span v-if="item.meta&&item.meta.title" slot="title">{{generateTitle(item.meta.title)}}</span> </template> <template v-for="child in item.children" v-if="!child.hidden"> <sidebar-item :is-nest="true" class="nest-menu" v-if="child.children&&child.children.length>0" :item="child" :key="child.path" :base-path="resolvePath(child.path)"></sidebar-item> <router-link v-else :to="resolvePath(child.path)" :key="child.name"> <el-menu-item :index="resolvePath(child.path)"> <svg-icon v-if="child.meta&&child.meta.icon" :icon-class="child.meta.icon"></svg-icon> <span v-if="child.meta&&child.meta.title" slot="title">{{generateTitle(child.meta.title)}}</span> </el-menu-item> </router-link> </template> </el-submenu>

其中v-if="hasOneShowingChildren(item.children) && !item.children[0].children&&!item.alwaysShow"表示当这个节点只有一个子元素,且这个节点的第一个子元素没有子元素时,显示一个特殊的菜单样式。而问题是item.children[0]多是一个隐藏的菜单(item.hidden === true),因此当这个表达式成立时,可能会渲染一个隐藏的菜单。参看最新的后台源码,做者已经修复了这个问题。

<template v-if="hasOneShowingChild(item.children,item) && (!onlyOneChild.children||onlyOneChild.noShowingChildren)&&!item.alwaysShow"> <app-link v-if="onlyOneChild.meta" :to="resolvePath(onlyOneChild.path)"> <el-menu-item :index="resolvePath(onlyOneChild.path)" :class="{'submenu-title-noDropdown':!isNest}"> <item :icon="onlyOneChild.meta.icon||(item.meta&&item.meta.icon)" :title="onlyOneChild.meta.title" /> </el-menu-item> </app-link> </template>
methods: {
    hasOneShowingChild(children = [], parent) {
      const showingChildren = children.filter(item => { if (item.hidden) { return false } else { // Temp set(will be used if only has one showing child) this.onlyOneChild = item return true } }) // When there is only one child router, the child router is displayed by default if (showingChildren.length === 1) { return true } // Show parent if there are no child router to display if (showingChildren.length === 0) { this.onlyOneChild = { ... parent, path: '', noShowingChildren: true } return true } return false } }

动态组件的建立

有时候咱们有不少相似的组件,只有一点点地方不同,咱们能够把这样的相似组件写到配置文件中,动态建立和引用组件

var vm = new Vue({ el: '#example', data: { currentView: 'home' }, components: { home: { /* ... */ }, posts: { /* ... */ }, archive: { /* ... */ } } }) <component v-bind:is="currentView"> <!-- 组件在 vm.currentview 变化时改变! --> </component>

动态菜单权限

因为菜单是根据权限动态生成的,因此默认的路由只须要几个不须要权限判断的页面,其余的页面的路由放在一个map对象asyncRouterMap中,
设置role为权限对应的编码

export const asyncRouterMap = [ { path: '/project', component: Layout, redirect: 'noredirect', name: 'Project', meta: { title: '项目管理', icon: 'project' }, children: [ { path: 'index', name: 'Index', component: () => import('@/views/project/index'), meta: { title: '项目管理', role: 'PRO-01' } },

导航守卫的判断,若是有token以及store.getters.allowGetRole说明用户已经登陆,routers为用户根据权限生成的路由树,若是不存在,则调用store.dispatch('GetMenu')请求用户菜单权限,再调用store.dispatch('GenerateRoutes')将获取的菜单权限解析成路由的结构。

router.beforeEach((to, from, next) => { if (whiteList.indexOf(to.path) !== -1) { next() } else { NProgress.start() // 判断是否有token 和 是否容许用户进入菜单列表 if (getToken() && store.getters.allowGetRole) { if (to.path === '/login') { next({ path: '/' }) NProgress.done() } else { if (!store.getters.routers.length) { // 拉取用户菜单权限 store.dispatch('GetMenu').then(() => { // 生成可访问的路由表 store.dispatch('GenerateRoutes').then(() => { router.addRoutes(store.getters.addRouters) next({ ...to, replace: true }) }) }) } else { next() } } } else { next('/login') NProgress.done() } } })

store中的actions

// 获取动态菜单菜单权限 GetMenu({ commit, state }) { return new Promise((resolve, reject) => { getMenu().then(res => { commit('SET_MENU', res.data) resolve(res) }).catch(error => { reject(error) }) }) }, // 根据权限生成对应的菜单 GenerateRoutes({ commit, state }) { return new Promise(resolve => { // 循环异步挂载的路由 var accessedRouters = [] asyncRouterMap.forEach((item, index) => { if (item.children && item.children.length) { item.children = item.children.filter(child => { if (child.hidden) { return true } else if (hasPermission(state.role.menu, child)) { return true } else { return false } }) } accessedRouters[index] = item }) // 将处理后的路由保存到vuex中 commit('SET_ROUTERS', accessedRouters) resolve() }) },

项目的部署和版本切换

目前项目有两个环境,分别为测试环境和生产环境,请求的接口地址配在\src\utils\global.js中,当部署生产环境时只须要将develop分支的代码合并到master分支,global.js不须要再额外更改地址

 

 

转载:http://www.javashuo.com/article/p-krkeffso-db.html

相关文章
相关标签/搜索