vue項(xiàng)目前端知識點(diǎn)整理【收藏】
微信授權(quán)后還能通過瀏覽器返回鍵回到授權(quán)頁
在導(dǎo)航守衛(wèi)中可以在 next({}) 中設(shè)置 replace: true 來重定向到改路由,跟 router.replace() 相同
router.beforeEach((to, from, next) => {
if (getToken()) {
...
} else {
// 儲存進(jìn)來的地址,供授權(quán)后跳回
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系統(tǒng)在微信瀏覽器input失去焦點(diǎn)后頁面不會自動回彈
初始的解決方案是input上綁定 onblur 事件,缺點(diǎn)是要綁定多次,且有的input存在于第三方組件中,無法綁定事件。
后來的解決方案是全局綁定 focusin 事件,因?yàn)?focusin 事件可以冒泡,被最外層的body捕獲。
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
}
}
在子組件中修改父組件傳遞的值時會報(bào)錯
vue中的props是單向綁定的,但如果props的類型為數(shù)組或者對象時,在子組件內(nèi)部改變props的值控制臺不會警告。因?yàn)閿?shù)組或?qū)ο笫堑刂芬?,但官方不建議在子組件內(nèi)改變父組件的值,這違反了vue中props單向綁定的思想。所以需要在改變props值的時候使用 $emit ,更簡單的方法是使用 .sync 修飾符。
// 在子組件中
this.$emit('update:title', newTitle)
//在父組件中
<text-document :title.sync="doc.title"></text-document>使用微信JS-SDK上傳圖片接口的處理
首先調(diào)用 wx.chooseImage() ,引導(dǎo)用戶拍照或從手機(jī)相冊中選圖。成功會拿到圖片的 localId ,再調(diào)用 wx.uploadImage() 將本地圖片暫存到微信服務(wù)器上并返回圖片的服務(wù)器端ID,再請求后端的上傳接口最后拿到圖片的服務(wù)器地址。
chooseImage(photoMustTake) {
return new Promise(resolve => {
var sourceType = (photoMustTake && photoMustTake == 1) ? ['camera'] : ['album', 'camera']
wx.chooseImage({
count: 1, // 默認(rèn)9
sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認(rèn)二者都有
sourceType: sourceType, // 可以指定來源是相冊還是相機(jī),默認(rèn)二者都有
success: function (res) {
// 返回選定照片的本地ID列表,localId可以作為img標(biāo)簽的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));
}
});
}
});
})
}
聊天室斷線重連的處理
由于后端設(shè)置了自動斷線時間,所以需要 socket 斷線自動重連。
在 data 如下幾個屬性, beginTime 表示當(dāng)前的真實(shí)時間,用于和服務(wù)器時間同步, openTime 表示 socket 創(chuàng)建時間,主要用于分頁,以及重連時的判斷, reconnection 表示是否斷線重連。
data() {
return {
reconnection: false,
beginTime: null,
openTime: null
}
}
初始化 socket 連接時,將 openTime 賦值為當(dāng)前本地時間, socket 連接成功后,將 beginTime 賦值為服務(wù)器返回的當(dāng)前時間,再設(shè)置一個定時器,保持時間與服務(wù)器一致。
發(fā)送消息時,當(dāng)有多個用戶,每個用戶的系統(tǒng)本地時間不同,會導(dǎo)致消息的順序錯亂。所以需要發(fā)送 beginTime 參數(shù)用于記錄用戶發(fā)送的時間,而每個用戶的 beginTime 都是與服務(wù)器時間同步的,可以解決這個問題。
聊天室需要分頁,而不同的時刻分頁的數(shù)據(jù)不同,例如當(dāng)前時刻有10條消息,而下個時刻又新增了2條數(shù)據(jù),所以請求分頁數(shù)據(jù)時,傳遞 openTime 參數(shù),代表以創(chuàng)建socket的時間作為查詢基準(zhǔn)。
// 創(chuàng)建socket
createSocket() {
_that.openTime = new Date().getTime() // 記錄socket 創(chuàng)建時間
_that.socket = new WebSocket(...)
}
// socket連接成功 返回狀態(tài)
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)
}
當(dāng)socket斷開時,判斷 beginTime 與當(dāng)前時間是否超過60秒,如果沒超過說明為非正常斷開連接不做處理。
_that.socket.onerror = evt => {
if (!_that.page.beginTime) {
_that.$vux.toast.text('網(wǎng)絡(luò)忙,請稍后重試')
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()
}
}
發(fā)送音頻時第一次授權(quán)問題
發(fā)送音頻時,第一次點(diǎn)擊會彈框提示授權(quán),不管點(diǎn)擊允許還是拒絕都會執(zhí)行 wx.startRecord() ,這樣再次調(diào)用錄音就會出現(xiàn)問題(因?yàn)樯弦粋€錄音沒有結(jié)束), 由于錄音方法是由 touchstart 事件觸發(fā)的,可以使用 touchcancel 事件捕獲彈出提示授權(quán)的狀態(tài)。
_that.$refs.btnVoice.addEventListener("touchcancel" ,function(event) {
event.preventDefault()
// 手動觸發(fā) touchend
_that.voice.isUpload = false
_that.voice.voiceText = '按住 說話'
_that.voice.touchStart = false
_that.stopRecord()
})
組件銷毀時,沒有清空定時器
在組件實(shí)例被銷毀后, setInterval() 還會繼續(xù)執(zhí)行,需要手動清除,否則會占用內(nèi)存。
mounted(){
this.timer = (() => {
...
}, 1000)
},
//最后在beforeDestroy()生命周期內(nèi)清除定時器
beforeDestroy() {
clearInterval(this.timer)
this.timer = null
}
watch監(jiān)聽對象的變化
watch: {
chatList: {
deep: true, // 監(jiān)聽對象的變化
handler: function (newVal,oldVal){
...
}
}
}
后臺管理系統(tǒng)模板問題
由于后臺管理系統(tǒng)增加了菜單權(quán)限,路由是根據(jù)菜單權(quán)限動態(tài)生成的,當(dāng)只有一個菜單的權(quán)限時,會導(dǎo)致這個菜單可能不顯示,參看模板的源碼:
<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" 表示當(dāng)這個節(jié)點(diǎn)只有一個子元素,且這個節(jié)點(diǎn)的第一個子元素沒有子元素時,顯示一個特殊的菜單樣式。而問題是 item.children[0] 可能是一個隱藏的菜單( item.hidden === true ),所以當(dāng)這個表達(dá)式成立時,可能會渲染一個隱藏的菜單。參看最新的后臺源碼,作者已經(jīng)修復(fù)了這個問題。
<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
}
}
動態(tài)組件的創(chuàng)建
有時候我們有很多類似的組件,只有一點(diǎn)點(diǎn)地方不一樣,我們可以把這樣的類似組件寫到配置文件中,動態(tài)創(chuàng)建和引用組件
var vm = new Vue({
el: '#example',
data: {
currentView: 'home'
},
components: {
home: { /* ... */ },
posts: { /* ... */ },
archive: { /* ... */ }
}
})
<component v-bind:is="currentView">
<!-- 組件在 vm.currentview 變化時改變! -->
</component>
動態(tài)菜單權(quán)限
由于菜單是根據(jù)權(quán)限動態(tài)生成的,所以默認(rèn)的路由只需要幾個不需要權(quán)限判斷的頁面,其他的頁面的路由放在一個map對象 asyncRouterMap 中,
設(shè)置 role 為權(quán)限對應(yīng)的編碼
export const asyncRouterMap = [
{
path: '/project',
component: Layout,
redirect: 'noredirect',
name: 'Project',
meta: { title: '項(xiàng)目管理', icon: 'project' },
children: [
{
path: 'index',
name: 'Index',
component: () => import('@/views/project/index'),
meta: { title: '項(xiàng)目管理', role: 'PRO-01' }
},
導(dǎo)航守衛(wèi)的判斷,如果有 token 以及 store.getters.allowGetRole 說明用戶已經(jīng)登錄, routers 為用戶根據(jù)權(quán)限生成的路由樹,如果不存在,則調(diào)用 store.dispatch('GetMenu') 請求用戶菜單權(quán)限,再調(diào)用 store.dispatch('GenerateRoutes') 將獲取的菜單權(quán)限解析成路由的結(jié)構(gòu)。
router.beforeEach((to, from, next) => {
if (whiteList.indexOf(to.path) !== -1) {
next()
} else {
NProgress.start()
// 判斷是否有token 和 是否允許用戶進(jìn)入菜單列表
if (getToken() && store.getters.allowGetRole) {
if (to.path === '/login') {
next({ path: '/' })
NProgress.done()
} else {
if (!store.getters.routers.length) {
// 拉取用戶菜單權(quán)限
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
// 獲取動態(tài)菜單菜單權(quán)限
GetMenu({ commit, state }) {
return new Promise((resolve, reject) => {
getMenu().then(res => {
commit('SET_MENU', res.data)
resolve(res)
}).catch(error => {
reject(error)
})
})
},
// 根據(jù)權(quán)限生成對應(yīng)的菜單
GenerateRoutes({ commit, state }) {
return new Promise(resolve => {
// 循環(huán)異步掛載的路由
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()
})
},
項(xiàng)目的部署和版本切換
目前項(xiàng)目有兩個環(huán)境,分別為測試環(huán)境和生產(chǎn)環(huán)境,請求的接口地址配在 \src\utils\global.js 中,當(dāng)部署生產(chǎn)環(huán)境時只需要將develop分支的代碼合并到master分支,global.js不需要再額外更改地址
總結(jié)
以上所述是小編給大家介紹的vue項(xiàng)目前端知識點(diǎn)整理,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復(fù)大家的!
相關(guān)文章
Vue基礎(chǔ)學(xué)習(xí)之項(xiàng)目整合及優(yōu)化
這篇文章主要給大家介紹了關(guān)于Vue基礎(chǔ)學(xué)習(xí)之項(xiàng)目整合及優(yōu)化的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Vue具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06
vue移動端項(xiàng)目中如何實(shí)現(xiàn)頁面緩存的示例代碼
這篇文章主要介紹了vue移動端項(xiàng)目中如何實(shí)現(xiàn)頁面緩存的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03

