vue項(xiàng)目中遇到的那些事。
前言
有好幾天沒更新文章了。這段實(shí)際忙著做了一個(gè)vue的項(xiàng)目笤喳,從 19 天前開始,到今天剛好 20 天碌宴,獨(dú)立完成杀狡。
做vue項(xiàng)目做這個(gè)項(xiàng)目一方面能為工作做一些準(zhǔn)備,一方面也精進(jìn)一下技術(shù)贰镣。
技術(shù)棧:vue2 + vuex + vue-router + webpack + ES6/7 + element-ui + vue-baidu-map + i18n + vue-awesome-swiper
做項(xiàng)目時(shí)總是有一些思考和踩過的坑捣卤,對(duì)以后有一定的幫助忍抽,今天就來寫寫做vue項(xiàng)目遇到的那些事。
假如你正準(zhǔn)備做項(xiàng)目或正在做項(xiàng)目一定看看董朝,說不定對(duì)你有所幫助鸠项。
正文
照例放上一些項(xiàng)目中用到的權(quán)威的官網(wǎng)
vue 官方api:https://cn.vuejs.org/
vue資源精選:http://vue.awesometiny.com/
vue GitHub地址:https://github.com/vuejs/vue
element-ui 官方中文api:http://element-cn.eleme.io/#/zh-CN/component/dropdown
vue-awesome-swiper GitHub地址: https://surmon-china.github.io/vue-awesome-swiper/
1.閱讀vue的風(fēng)格指南再開始你的項(xiàng)目(最重要)
2.vue項(xiàng)目中data可以視為一個(gè)函數(shù)
<script>
export default {
data () {
// 可以在這里寫很多的前置數(shù)據(jù)操作
return {}
}
}
</script>
例如:
<script>
export default {
data () {
// 可以在這里寫很多的前置數(shù)據(jù)操作
// 不在首頁(yè)時(shí)隱藏切換語言
let showLanguageList
if (
this.$route.path === '/Home' ||
this.$route.path === '/' ||
) {
showLanguageList = true
} else {
showLanguageList = false
}
return {
showLanguageList: showLanguageList
}
}
}
</script>
3.路由帶參
路由帶參:點(diǎn)擊查看官網(wǎng)說明
-
我們可以在路由切換時(shí)綁定參數(shù)
在App.vue文件中監(jiān)聽路由綁定參數(shù)
watch: {
$route (to, from) {
// 在路由上綁定語言和公司編號(hào)
this.$router.replace({
path: this.$router.path,
query: {
languageCode: '中文',
companyCode: '阿里巴巴'
}
})
}
}
-
函數(shù)query傳參可以和路由綁定id一起使用
路由綁定ID:
const User = {
template: '<div>User {{ $route.params.id }}</div>'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User }
]
})
效果:
4.解決整個(gè)項(xiàng)目的數(shù)據(jù)刷新問題
需求:在項(xiàng)目中經(jīng)常會(huì)用到點(diǎn)擊某個(gè)按鈕或者更新某個(gè)參數(shù)時(shí)作媚,整個(gè)項(xiàng)目的后臺(tái)數(shù)據(jù)都從新請(qǐng)求一遍或者刷新整個(gè)頁(yè)面恩急。
-
類似F5刷新
this.$router.go(0);
location.reload()
//這兩種方式都相當(dāng)于f5刷新巨柒,頁(yè)面會(huì)有卡頓妇垢,白屏的情況胡嘿,用戶體驗(yàn)極差
-
通過v-if的顯示蝶柿,消失撰筷,刷新數(shù)據(jù)
適用于整個(gè)項(xiàng)目的數(shù)據(jù)刷新夏块,當(dāng)然也可以用于刷新部分頁(yè)面
頁(yè)面刷新相對(duì)流暢遥赚,比較推薦的一種方法
在App.vue中:
<template>
<div id="app">
<router-view v-if="isRouterAlive" />
</div>
</template>
<script>
export default {
name: 'App',
provide () {
return {
reload: this.reload
}
},
data () {
return {
isRouterAlive: true
}
},
methods: {
reload () {
this.isRouterAlive = false
this.$nextTick(function () {
this.isRouterAlive = true
})
}
}
}
</script>
<style>
</style>
在子組件中扬舒,當(dāng)我們需要刷新數(shù)據(jù)時(shí):
<template>
<div @click="onSubmit_name"></div>
</template>
<script>
export default {
data () {
return {}
},
inject: ['reload'], //引入方法
methods: {
onSubmit_name() {this.reload()} //需要刷新數(shù)據(jù)的時(shí)候調(diào)用reload方法
}
</script>
<style>
</style>
-
利用路由的replace方法
這種方式是進(jìn)入一個(gè)空白頁(yè),在空白頁(yè)里面跳轉(zhuǎn)回原來的頁(yè)面凫佛,這種方式頁(yè)面刷新相對(duì)流暢`
// 需要刷新數(shù)據(jù)的頁(yè)面,
refresh () {
this.$router.replace({
path: '/refresh',
query: {
t: Date.now() //攜帶必要的路由參數(shù)
}
})
}
// refresh.vue頁(yè)面中里有路由鉤子晨炕,直接返回前一個(gè)頁(yè)面
<script>
export default {
beforeRouteEnter(to, from, next) {
next(vm => {
vm.$router.replace(from.path)
})
}
}
</script>
5.element-ui導(dǎo)航欄與路由
-
激活導(dǎo)航跳轉(zhuǎn)對(duì)應(yīng)路由
在element-ui的導(dǎo)航中毫炉,官方讓我們能和vue的router無縫對(duì)接瓮栗,實(shí)現(xiàn)綁定路由,同樣可以根據(jù)路由實(shí)現(xiàn)對(duì)應(yīng)導(dǎo)航欄高亮费奸。
router 是否使用 vue-router 的模式进陡,啟用該模式會(huì)在激活導(dǎo)航時(shí)以 index 作為 path 進(jìn)行路由跳轉(zhuǎn) boolean — false
請(qǐng)看圖中標(biāo)紅的位置货邓,添加router以后,每次激活導(dǎo)航時(shí)以 index 作為 path 進(jìn)行路由跳轉(zhuǎn)
<el-menu router :default-active="activeIndex" class="el-menu-vertical-demo hidden-sm-and-up" mode="vertical" :collapse="isCollapse" style="height:62px;float:right;width:100%;border:0;z-index:100"
background-color="#222" text-color="#fff" active-text-color="#e42828">
<el-submenu index="1">
<template slot="title">
<i class="el-icon-menu"></i>
<span slot="title">{{$t('home.home')}}</span>
</template>
<el-menu-item-group>
<el-menu-item index="/Pages">{{$t('home.home')}}</el-menu-item>
<el-menu-item index="/PagesAbout">{{$t('home.about')}}</el-menu-item>
<el-menu-item index="/PagesProductList">{{$t('home.product')}}</el-menu-item>
<el-menu-item index="/PagesService">{{$t('home.service')}}</el-menu-item>
<el-menu-item index="/PagesNewsList">{{$t('home.news')}}</el-menu-item>
<el-menu-item index="/PagesRecruitmentList">{{$t('home.recruitment')}}</el-menu-item>
<el-menu-item index="/PagesContact">{{$t('home.contact')}}</el-menu-item>
<el-menu-item index="/PagesDownload">{{$t('home.download')}}</el-menu-item>
</el-menu-item-group>
</el-submenu>
</el-menu>
-
根據(jù)對(duì)應(yīng)路由實(shí)現(xiàn)對(duì)應(yīng)導(dǎo)航高亮
請(qǐng)看如下代碼四濒,重點(diǎn)關(guān)注紅色部分
<el-menu router :default-active="activeIndex" class="el-menu-demo hidden-xs-only" mode="horizontal" style="height:62px;float:right;width:100%;border:0;z-index:100"
background-color="#222" text-color="#fff" active-text-color="#e42828">
<el-menu-item index="/Pages">{{$t('home.home')}}</el-menu-item>
<el-menu-item index="/PagesAbout">{{$t('home.about')}}</el-menu-item>
<el-menu-item index="/PagesProductList">{{$t('home.product')}}</el-menu-item>
<el-menu-item index="/PagesService">{{$t('home.service')}}</el-menu-item>
<el-menu-item index="/PagesNewsList">{{$t('home.news')}}</el-menu-item>
<el-menu-item index="/PagesRecruitmentList">{{$t('home.recruitment')}}</el-menu-item>
<el-menu-item index="/PagesContact">{{$t('home.contact')}}</el-menu-item>
<el-menu-item index="/PagesDownload">{{$t('home.download')}}</el-menu-item>
</el-menu>
我們可以利用vue的特性盗蟆,動(dòng)態(tài)的改變default-active的值來改變導(dǎo)航欄的高亮喳资,當(dāng)然我們也可以通過截取的方式,
只要路由中有一部分路由和index相同則激活鲜滩。
default-active 當(dāng)前激活菜單的 index string
代碼如下:
URL:http://localhost:8080/#/PagesNewsList/4dd8136dec5c48bcb223e9ef1fa5714f?languageCode=zh-CN&companyCode=0000 let pathss = this.$route.path.split('/')
let pathss = this.$route.path.split('/') //截取路由
data () {
return {
activeIndex: '/' + pathss[1] //將路由中紅色的地方設(shè)置為對(duì)應(yīng)導(dǎo)航高亮。不可忘記‘/’榜聂,注意下標(biāo)越界嗓蘑。
}
}
6.如何實(shí)現(xiàn)單頁(yè)面的title設(shè)置?
網(wǎng)上也有很多方法桩皿,但我這里強(qiáng)烈推薦一個(gè)插件泄隔,方便又實(shí)用。
-
下載安裝插件依賴
npm install vue-wechat-title --save
-
在main.js中引入插件
import VueWechatTitle from 'vue-wechat-title'
Vue.use(VueWechatTitle)
-
路由定義(只截取一部分)
// ...
const routes = [
{
name: 'Home',
path: '/home',
meta: {
title: '首頁(yè)'
},
component: require('../views/Home.vue')
},
{
name: 'Order',
path: '/order',
meta: {
title: '訂單'
},
component: require('../views/Order.vue')
},
{
name: 'UCenter',
path: '/ucenter',
meta: {
title: '用戶中心'
},
component: require('../views/UCenter.vue')
}
]
// ...
- App.vue 建議全局只使用一次該指令 標(biāo)題可用vuex或者router中定義 不要多處使用!!
<!-- 任意元素中加 v-wechat-title 指令 建議將標(biāo)題放在 route 對(duì)應(yīng)meta對(duì)象的定義中 -->
<div v-wechat-title="$route.meta.title"></div>
<!--or-->
<router-view v-if="isRouterAlive" v-wechat-title='$route.meta.title' />
7.路由加載方式
路由都有兩種加載方式逻澳。
-
一種是懶加載
只在你點(diǎn)擊或者訪問的時(shí)候加載巷燥。建議用于不經(jīng)常訪問的路由赡盘。
路由配置如下:
{
path: '/Home',
name: 'Home',
component: () => import('./views/Home.vue'),
meta: {
title: '首頁(yè)'
}
}
-
一種是普通加載
在項(xiàng)目啟動(dòng)時(shí)就渲染好靜態(tài)頁(yè)面号枕,建議用于經(jīng)常訪問的路由,增加效率以及提升體驗(yàn)钝腺。
import PagesHome from './pages/home/Home.vue'
{
path: '/Pages',
name: '/Pages',
component: PagesHome,
meta: {
title: '首頁(yè)'
}
}
8.默認(rèn)路由以及404頁(yè)面
直接在router.js頁(yè)面中填入下面代碼
export default new Router({
routes: [
{
path: '/', // 項(xiàng)目啟動(dòng)頁(yè)
redirect:'/Home' // 重定向到下方聲明的路由
},
{
path: '*', // 404 頁(yè)面
component: () => import('./notFind') // 或者使用component也可以的
},
]
})
9.數(shù)據(jù)持久化
做vue項(xiàng)目時(shí)艳狐,為了防止f5以后數(shù)據(jù)重置皿桑,我們想到了數(shù)據(jù)持久化
-
巧用vue-cookie插件
傳送門:https://www.npmjs.com/package/vue-cookie
npm方式安裝
npm install vue-cookie --save
在main.js/app.js中引用
// Require dependencies
var Vue = require('vue');
var VueCookie = require('vue-cookie');
// Tell Vue to use the plugin
Vue.use(VueCookie);
示例:
// From some method in one of your Vue components
this.$cookie.set('test', 'Hello world!', 1);
// This will set a cookie with the name 'test' and the value 'Hello world!' that expires in one day
// To get the value of a cookie use
this.$cookie.get('test');
// To delete a cookie use
this.$cookie.delete('test');
高級(jí)示例:
// Setting the cookie Domain
this.$cookie.set('test', 'Random value', {expires: 1, domain: 'localhost'});
// As this cookie is set with a domain then if you wish to delete it you have to provide the domain when calling delete
this.$cookie.delete('test', {domain: 'localhost'});
// Customizing expires
var date = new Date;
date.setDate(date.getDate() + 21);
this.$cookie.set('dateObject', 'A date object', { expires: date });
this.$cookie.set('dateString', 'A parsable date string', { expires: date.toGMTString() });
this.$cookie.set('integer', 'Seven days later', { expires: 7 });
this.$cookie.set('stringSuffixY', 'One year later', { expires: '1Y' });
this.$cookie.set('stringSuffixM', 'One month later', { expires: '1M' });
this.$cookie.set('stringSuffixD', 'One day later', { expires: '1D' });
this.$cookie.set('stringSuffixh', 'One hour later', { expires: '1h' });
this.$cookie.set('stringSuffixm', 'Ten minutes later', { expires: '10m' });
this.$cookie.set('stringSuffixs', 'Thirty seconds later', { expires: '30s' });
(我們也可以在vuex的store中使用)
-
巧用vuex-persistedstate插件
前提:已經(jīng)安裝并使用vuex诲侮。
安裝vuex-persistedstate
npm install vuex-persistedstate
在vuex的store文件的index.js中引用
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import state from './state'
import mutations from './mutations'
Vue.use(Vuex)
export default new Vuex.Store({
state,
mutations,
plugins: [createPersistedState()]
})
10.vue官網(wǎng)的推薦資源中,基本能找到我們想要的資源
1. 推薦一個(gè)地圖插件:vue-baidu-map(百度地圖)vue-google-maps(谷歌地圖)
安裝
npm i --save vue-baidu-map
在main.js中引入
// 引入百度地圖插件
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, {
// ak 是在百度地圖開發(fā)者平臺(tái)申請(qǐng)的密鑰 詳見 http://lbsyun.baidu.com/apiconsole/key */
ak: 'Zgbme5XaLreej7Oribs9yk317sOFG3OP'
})
使用示例:
<baidu-map class="map" :center="center" :zoom="zoom" @ready="handler">
<bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>
<bm-marker :position="{lng: this.$store.state.companyObject.longitude, lat: this.$store.state.companyObject.latitude}" :dragging="false"animation="BMAP_ANIMATION_BOUNCE">
<bm-label :content="this.$store.state.companyObject.transname" :labelStyle="{color: 'red', fontSize : '14px'}" :offset="{width: -35, height: 25}" />
</bm-marker>
<bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
<bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_TOP_LEFT"></bm-map-type>
</baidu-map>
export default {
name: 'Contact',
components: {
ContactUs
},
data () {
return {
center: {
lng: '26.515515',
lat:'103.54548841'
},
zoom: 15
}
},
methods: {
handler ({ BMap, map }) {
this.center.lng ='26.515515'
this.center.lat = '103.54548841'
this.zoom = 15 } } }
2. 推薦一個(gè)vue輪播插件:vue-awesome-swiper
安裝
npm install vue-awesome-swiper --save
引用:
import Vue from 'vue'
import VueAwesomeSwiper from 'vue-awesome-swiper'
// require styles
import 'swiper/dist/css/swiper.css'
Vue.use(VueAwesomeSwiper, /* { default global options } */)
示例:(每個(gè)都是vue項(xiàng)目的示例绽慈,在右上角都有對(duì)應(yīng)代碼的鏈接)
https://surmon-china.github.io/vue-awesome-swiper/
3.推薦一個(gè)vue國(guó)際化插件:vue-i18n
文檔:http://kazupon.github.io/vue-i18n/
使用方法請(qǐng)參考文檔辈毯,非常詳盡搜贤。element-ui已經(jīng)兼容 vue-i18n@5.x
結(jié)尾
vue現(xiàn)在已經(jīng)相當(dāng)成熟入客,能做的事情還有很多,大家在使用過程中如果有什么問題桌硫,歡迎交流,一起學(xué)習(xí)卓舵,一起進(jìn)步膀钠。
年前就寫好了。想著過年大家都沒心思看融击,就拖到現(xiàn)在雳窟。
代碼是敲不玩的,這輩子都不可能敲完了拇涤,只能不斷學(xué)習(xí)誉结。哈哈
小舟從此逝,江海寄余生掉盅。 --狐貍
歡迎大家關(guān)注公眾號(hào)趾痘,不定時(shí)干貨稀轨,只做有價(jià)值的輸出
作者:Dawnzhang
出處:https://www.cnblogs.com/clwydjgs/p/10291136.html
版權(quán):本文版權(quán)歸作者
轉(zhuǎn)載:歡迎轉(zhuǎn)載,但未經(jīng)作者同意瓦侮,必須保留此段聲明;必須在文章中給出原文連接肚吏;
往期文章:
Visual Studio Code(VS code)你們都在用嗎罚攀?或許你們需要看一下這篇博文