vue項(xiàng)目中遇到的那些事

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)目(最重要)

image

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 }
  ]
})

效果:

image

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í)用。

vue-wechat-title

  • 下載安裝插件依賴

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)的推薦資源中,基本能找到我們想要的資源

image

1. 推薦一個(gè)地圖插件:vue-baidu-map(百度地圖)vue-google-maps(谷歌地圖)

文檔:https://dafrok.github.io/vue-baidu-map/

安裝

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í)誉结。哈哈

小舟從此逝,江海寄余生掉盅。 --狐貍

PKF8CRGT6PF@UP2A9W585EJ.png

歡迎大家關(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)你們都在用嗎罚攀?或許你們需要看一下這篇博文

你們都在用IntelliJ IDEA嗎?或許你們需要看一下這篇博文

你真的了解博客園的目錄么斋泄。炫掐。

博客園博客排版(js樣式實(shí)例)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市旗唁,隨后出現(xiàn)的幾起案子痹束,更是在濱河造成了極大的恐慌,老刑警劉巖屎媳,帶你破解...
    沈念sama閱讀 211,194評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件抹蚀,死亡現(xiàn)場(chǎng)離奇詭異环壤,居然都是意外死亡钞诡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,058評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門接箫,熙熙樓的掌柜王于貴愁眉苦臉地迎上來朵诫,“玉大人,你說我怎么就攤上這事废累。” “怎么了日缨?”我有些...
    開封第一講書人閱讀 156,780評(píng)論 0 346
  • 文/不壞的土叔 我叫張陵掖看,是天一觀的道長(zhǎng)哎壳。 經(jīng)常有香客問我,道長(zhǎng)归榕,這世上最難降的妖魔是什么蹲坷? 我笑而不...
    開封第一講書人閱讀 56,388評(píng)論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮级乐,結(jié)果婚禮上县匠,老公的妹妹穿的比我還像新娘。我一直安慰自己贼穆,他們只是感情好兰粉,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,430評(píng)論 5 384
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著愕秫,像睡著了一般焰络。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上甜孤,一...
    開封第一講書人閱讀 49,764評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音囱稽,去河邊找鬼二跋。 笑死,一個(gè)胖子當(dāng)著我的面吹牛吞获,可吹牛的內(nèi)容都是我干的谚鄙。 我是一名探鬼主播,決...
    沈念sama閱讀 38,907評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼烤黍,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼速蕊!你這毒婦竟也來了娘赴?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,679評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤唉锌,失蹤者是張志新(化名)和其女友劉穎竿奏,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體绿语,經(jīng)...
    沈念sama閱讀 44,122評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡平痰,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,459評(píng)論 2 325
  • 正文 我和宋清朗相戀三年宗雇,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了莹规。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,605評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡舞虱,死狀恐怖矾兜,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情椅寺,我是刑警寧澤,帶...
    沈念sama閱讀 34,270評(píng)論 4 329
  • 正文 年R本政府宣布桐玻,位于F島的核電站镊靴,受9級(jí)特大地震影響链韭,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜敞峭,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,867評(píng)論 3 312
  • 文/蒙蒙 一儡陨、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧嫌褪,春花似錦胚股、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,734評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至谭胚,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間胡控,已是汗流浹背旁趟。 一陣腳步聲響...
    開封第一講書人閱讀 31,961評(píng)論 1 265
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留癣猾,地道東北人余爆。 一個(gè)月前我還...
    沈念sama閱讀 46,297評(píng)論 2 360
  • 正文 我出身青樓蛾方,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親桩砰。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,472評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容