7種經(jīng)常使用的Vue.js模式和36個實用Vue開發(fā)技巧,你知道多少?

2021-4-22    前端達(dá)人

7種Vue.js模式

1.處理加載狀態(tài)

在大型應(yīng)用程序中,我們可能需要將應(yīng)用程序劃分為更小的塊,只有在需要時才從服務(wù)器加載組件。為了使這一點更容易,Vue允許你將你的組件定義為一個工廠函數(shù),它異步解析你的組件定義。Vue只有在需要渲染組件時才會觸發(fā)工廠函數(shù),并將緩存結(jié)果,以便將來重新渲染。2.3版本的新功能是,異步組件工廠也可以返回一個如下格式的對象。

const AsyncComponent = () => ({
  // 要加載的組件(應(yīng)為Promise)
  component: import('./MyComponent.vue'),
  // 異步組件正在加載時要使用的組件
  loading: LoadingComponent,
  // 加載失敗時使用的組件
  error: ErrorComponent,
  // 顯示加載組件之前的延遲。默認(rèn)值:200ms。
  delay: 200,
  // 如果提供并超過了超時,則會顯示error組件。默認(rèn)值:無窮。
  timeout: 3000
}) 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

通過這種方法,你有額外的加載和錯誤狀態(tài)、組件獲取的延遲和超時等選項。

2.廉價的“v-once”靜態(tài)組件

在Vue中渲染純HTML元素的速度非常快,但有時你可能有一個包含大量靜態(tài)內(nèi)容的組件。在這種情況下,你可以通過在根元素中添加 v-once 指令來確保它只被評估一次,然后進(jìn)行緩存,就像這樣。

Vue.component('terms-of-service', {
  template: `
    <div v-once>
      <h1>Terms of Service</h1>
      ... a lot of static content ...
    </div>
  `
}) 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

3.遞歸組件

組件可以在自己的模板中遞歸調(diào)用自己,但是,它們只能通過 name 選項來調(diào)用。

如果你不小心,遞歸組件也可能導(dǎo)致無限循環(huán):

name: 'stack-overflow',
template: '<div><stack-overflow></stack-overflow></div>' 
  • 1
  • 2

像上面這樣的組件會導(dǎo)致“超過最大堆棧大小”的錯誤,所以要確保遞歸調(diào)用是有條件的即(使用 v-if 最終將為 false

4.內(nèi)聯(lián)模板

當(dāng)特殊屬性 inline-template 存在于一個子組件上時,該組件將使用它的內(nèi)部內(nèi)容作為它的模板,而不是將其視為分布式內(nèi)容,這允許更靈活的模板編寫。

<my-component inline-template>
  <div>
    <p>These are compiled as the component's own template.</p>
    <p>Not parent's transclusion content.</p>
  </div>
</my-component> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

5.動態(tài)指令參數(shù)

指令參數(shù)可以是動態(tài)的。例如,在 v-mydirective:[argument]=“value" 中, argument 可以根據(jù)組件實例中的數(shù)據(jù)屬性更新!這使得我們的自定義指令可以靈活地在整個應(yīng)用程序中使用。

這是一條指令,其中可以根據(jù)組件實例更新動態(tài)參數(shù):

<div id="dynamicexample">
  <h3>Scroll down inside this section ↓</h3>
  <p v-pin:[direction]="200">I am pinned onto the page at 200px to the left.</p>
</div>
Vue.directive('pin', {
  bind: function (el, binding, vnode) {
    el.style.position = 'fixed'
    var s = (binding.arg == 'left' ? 'left' : 'top')
    el.style[s] = binding.value + 'px'
  }
})

new Vue({
  el: '#dynamicexample',
  data: function () {
    return {
      direction: 'left'
    }
  }
}) 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

6.事件和鍵修飾符

對于 .passive、.capture 和 .once 事件修飾符,Vue提供了可與 on 一起使用的前綴:

例如:

on: {
  '!click': this.doThisInCapturingMode,
  '~keyup': this.doThisOnce,
  '~!mouseover': this.doThisOnceInCapturingMode
} 
  • 1
  • 2
  • 3
  • 4
  • 5

對于所有其他的事件和鍵修飾符,不需要專有的前綴,因為你可以在處理程序中使用事件方法。

7.依賴注入(Provide/Inject)

有幾種方法可以讓兩個組件在 Vue 中進(jìn)行通信,它們各有優(yōu)缺點。在2.2版本中引入的一種新方法是使用Provide/Inject的依賴注入。

這對選項一起使用,允許一個祖先組件作為其所有子孫的依賴注入器,無論組件層次結(jié)構(gòu)有多深,只要它們在同一個父鏈上。如果你熟悉React,這與React的上下文功(context)能非常相似。

// parent component providing 'foo'
var Provider = {
  provide: {
    foo: 'bar'
  },
  // ...
}

// child component injecting 'foo'
var Child = {
  inject: ['foo'],
  created () {
    console.log(this.foo) // => "bar"
  }
  // ...
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

36個Vue開發(fā)技巧

1.require.context()

1.場景:如頁面需要導(dǎo)入多個組件,原始寫法:

importtitleComfrom'@/components/home/titleCom'
importbannerComfrom'@/components/home/bannerCom'
importcellComfrom'@/components/home/cellCom'
components:{titleCom,bannerCom,cellCom} 
  • 1
  • 2
  • 3
  • 4

2.這樣就寫了大量重復(fù)的代碼,利用require.context可以寫成

constpath=require('path')
constfiles=require.context('@/components/home',false,/\.vue$/)
constmodules={}
files.keys().forEach(key=>{
constname=path.basename(key,'.vue')
modules[name]=files(key).default||files(key)
})
components:modules 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

這樣不管頁面引入多少組件,都可以使用這個方法

3.API方法

實際上是webpack的方法,vue工程一般基于webpack,所以可以使用require.context(directory,useSubdirectories,regExp)
接收三個參數(shù):directory:說明需要檢索的目錄useSubdirectories:是否檢索子目錄regExp:匹配文件的正則表達(dá)式,一般是文件名

2.watch

2.1常用用法

1.場景:表格初始進(jìn)來需要調(diào)查詢接口getList(),然后input改變會重新查詢

created(){
    this.getList()
},
watch:{
     inpVal(){
        this.getList()
      }
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

2.2立即執(zhí)行

2.可以直接利用watch的immediate和handler屬性簡寫

watch:{
     inpVal:{
        handler:'getList',
             immediate:true
        }
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2.3深度監(jiān)聽

3.watch的deep屬性,深度監(jiān)聽,也就是監(jiān)聽復(fù)雜數(shù)據(jù)類型

watch:{
     inpValObj:{
        handler(newVal,oldVal{
            console.log(newVal)
            console.log(oldVal)
     },
     deep:true
   }
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

此時發(fā)現(xiàn)oldVal和newVal值一樣;因為它們索引同一個對象/數(shù)組,Vue不會保留修改之前值的副本;所以深度監(jiān)聽雖然可以監(jiān)聽到對象的變化,但是無法監(jiān)聽到具體對象里面那個屬性的變化

7種vue模式還能和大家說完,但36個vue開發(fā)技巧太多啦,文章篇幅也不夠,小編寫了兩個例子,沒寫出來的開發(fā)技巧小伙伴們請點擊這里領(lǐng)取Vue開發(fā)必須知道的36個技巧PDF文檔。

轉(zhuǎn)自:csdn 論壇 作者:李不要熬夜

藍(lán)藍(lán)設(shè)計www.bouu.cn )是一家專注而深入的界面設(shè)計公司,為期望卓越的國內(nèi)外企業(yè)提供卓越的UI界面設(shè)計、BS界面設(shè)計 、 cs界面設(shè)計 、 ipad界面設(shè)計 、 包裝設(shè)計 、 圖標(biāo)定制 、 用戶體驗 、交互設(shè)計、 網(wǎng)站建設(shè) 、平面設(shè)計服務(wù)


分享本文至:

日歷

鏈接

個人資料

存檔