vue項目技術隨筆

最近都在作vue相關的項目,在公司推行先後端分離,重構之前的項目,真的好忙,一個項目接着一個,爬不完的坑,不說了,說多了都是眼淚。開始正文了!!!vue

  • Vue 路由切換時頁面內容沒有從新加載
    問題緣由:在組件mounted鉤子中調用的刷新頁面內容,但測試發現這個鉤子沒有被調用。後來發現App.vue中使用了: keep-alive是Vue的內置組件,能在組件切換過程當中將狀態保留在內存中,防止重複渲染DOM。這就是問題所在了。

解決辦法:ios

使用Vue組件切換過程鉤子activated(keep-alive組件激活時調用),而不是掛載鉤子mounted:vuex

<script>
export default {
  activated: function() {
    this.getData()
  }
}
</script>
複製代碼

參考網址關於keep-alive組件的鉤子:https://cn.vuejs.org/v2/api/#activatedaxios

  • 文件導出方式
    項目中涉及到文件導出,分xml和excel導出。不一樣的文件導出格式不一樣,須要根據文件類型判斷導出格式。
exportAllData(val){
    //所有導出
    if(!val){
      this.exportFile(this.exportAllType);
    }
},
exportFile(exportType){
    let url='';//接口地址
    this.$axios.get(url,{responseType: 'arraybuffer'}).then(res => {
      this.download(res.data,exportType);
    },res => {
      this.$Message.error('導出失敗');
    });
},
download (data,exportType) {
    if (!data) {
      return
    }
    let exportGs='';
    if(exportType==='excel'){
      exportGs='application/vnd.ms-excel';
    }else if(exportType==='xml'){
      exportGs='text/xml';
    }
    let url = window.URL.createObjectURL(new Blob([data],{type: exportGs}));
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url;
    link.setAttribute('download', '文件');
    document.body.appendChild(link)
    link.click();
 }
複製代碼
  • 在vue多層次組件監聽動做和屬性的時候可使用以下方式進行監聽
v-bind="$attrs" v-on="$listeners"
複製代碼

Vue 2.4 版本提供了這種方法,將父組件中不被認爲 props特性綁定的屬性傳入子組件中,一般配合 interitAttrs 選項一塊兒使用。之因此要提到這兩個屬性,是由於二者的出現使得組件之間跨組件的通訊在不依賴 vuex 和事件總線的狀況下變得簡潔,業務清晰。後端

好比組件A=>B組件=>C組件等,這種多層級組件,A組件向C組件傳遞數據或者C組件的事件要觸發A組件中的事件的話,就能夠在B組件中寫成

<template>
 <div>
    <span>{{child1}}<span>
 <!-- C組件中能直接觸發test的緣由在於 B組件調用C組件時 使用 v-on 綁定了$listeners 屬性 -->
 <!-- 經過v-bind 綁定$attrs屬性,C組件能夠直接獲取到A組件中傳遞下來的props(除了B組件中props聲明的) -->
 <c v-bind="$attrs" v-on="$listeners"></c>
 </div>
</template>
<script>
 import c from './c.vue';
 export default {
 props: ['child1'],
 data () {
 return {};
 },
 inheritAttrs: false,
 components: { c },
 mounted () {
    this.$emit('test1');
 }
 };
</script>
複製代碼

C組件api

<template>
 <div>
    <span>{{child2}}<span>
 </div>
</template>
<script>
 export default {
 props: [child2'], data () { return {}; }, inheritAttrs: false, mounted () { this.$emit('test2'); } }; </script> 複製代碼

A組件:bash

<template>
 <div id="app">
    <b :child1="child1" :child2="child2" @test1="test1" @test2="test2"></b>
 </div>
</template>
<script>
 import b from './b.vue';
 export default {
 data () {
 return {
     child1:'hello child1',
     child2:'hello child2'
 };
 },
 components: { b },
 methods: {
 test1 () {
 console.log('test1');
 },
 test2 () {
 console.log('test2');
 }
 }
 };
</script>
複製代碼

記錄平常開發中用到的一些知識點,權當一次總結吧。app

相關文章
相關標籤/搜索