Vue高版本中一些新特性的使用詳解

1、深度做用選擇器( >>> )css

嚴格來講,這個應該是vue-loader的功能。」vue-loader」: 「^12.2.0」html

在項目開發中,若是業務比較複雜,特別像中臺或B端功能頁面都不可避免的會用到第三方組件庫,產品有時會想對這些組件進行一些UI方面的定製。若是這些組件採用的是有做用域的CSS,父組件想要定製第三方組件的樣式就比較麻煩了。前端

深度做用選擇器( >>> 操做符)能夠助你一臂之力。vue

<template>
<div>
  <h1 class="child-title">
    若是你但願 scoped 樣式中的一個選擇器可以做用得「更深」,例如影響子組件,你可使用 >>> 操做
  </h1>
</div>
</template>
 
<script>
export default {
  name: 'child',
  data() {
    return {
    }
  }
}
</script>
 
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.child-title {
  font-size: 12px;
}
</style>

前端全棧學習交流圈:866109386,面向1-3經驗年前端開發人員,幫助突破技術瓶頸,提高思惟能力webpack

上面的child組件中 .child-title 的做用域CSS設定字體大小爲12px,如今想在父組件中定製爲大小20px,顏色爲紅色。git

<template>
<div>
  <child class="parent-custom"></child>
</div>
</template>
<script>
import Child from './child';
export default {
  name: 'parent',
  components:{
    Child
  },
  data() {
    return {
    }
  }
}
</script>
 
<style>
.parent-custom >>> .child-title {
  font-size:20px;
  color: red;
}
</style>
 
效果妥妥的。可是別高興太早,注意到上面的style使用的是純css語法,若是採用less語法,你可能會收到一條webpack的報錯信息。
 
<style lang="less">
.parent-custom {
   >>> .child-title {
    font-size:20px;
    color: red;
  }
}
</style>

前端全棧學習交流圈:866109386,面向1-3經驗年前端開發人員,幫助突破技術瓶頸,提高思惟能力github

ERROR in ./~/css-loader!./~/vue-loader/lib/style-compiler?{"vue":true,"id":"data-v-960c5412","scoped":false,"hasInlineConfig":false}!./~/postcss-loader!./~/less-loader!./~/vue-loader/lib/selector.js?type=styles&index=0!./src/components/parent.vue
Module build failed: Unrecognised input
 @ /src/components/parent.vue (line 22, column 6)
 near lines:
  .parent-custom {
    >>> .child-title {
      font-size:20px;

上面的報錯信息實際上是less語法不認識 >>>。(less的github issue上有人提議支持>>>操做符,但本文使用的v2.7.3會有這個問題)web

解決方案是採用的less的轉義(scaping)和變量插值(Variable Interpolation)api

<style lang="less">
@deep: ~'>>>';
.parent-custom {
   @{deep} .child-title {
    font-size:20px;
    color: red;
  }
}
</style>

對於其餘的css預處理器,由於沒怎麼用,不妄加評論,照搬一下文檔的話。數組

有些像 Sass 之類的預處理器沒法正確解析 >>>。這種狀況下你可使用 /deep/ 操做符取而代之——這是一個 >>> 的別名,一樣能夠正常工做。

2、組件配置項inheritAttrs、組件實例屬性$attrs$listeners

2.4.0新增

組件配置項 inheritAttrs

咱們都知道假如使用子組件時傳了a,b,c三個prop,而子組件的props選項只聲明瞭a和b,那麼渲染後c將做爲html自定義屬性顯示在子組件的根元素上。

若是不但願這樣,能夠設置子組件的配置項 inheritAttrs:false,根元素就會乾淨多了。

<script>
export default {
  name: 'child',
  props:['a','b'],
  inheritAttrs:false
}
</script>

組件實例屬性$attrs$listeners

先看看vm.$attrs文檔上是怎麼說的

vm.$attrs

類型:{ [key: string]: string } 只讀 包含了父做用域中不做爲 prop 被識別 (且獲取) 的特性綁定 (class 和 style 除外)。當一個組件沒有聲明任何 prop 時,這裏會包含全部父做用域的綁定 (class 和 style 除外),而且能夠經過 v-bind=」$attrs」 傳入內部組件——在建立高級別的組件時很是有用。

概括起來就是兩點:

vm.$attrs是組件的內置屬性,值是父組件傳入的全部prop中未被組件聲明的prop(class和style除外)。

仍是之前面的child組件舉例

//parent.vue
<template>
  <div>
    <child class="parent-custom" a="a" b="b" c="c"></child>
  </div>
</template>
 
//child.vue
<script>
export default {
  name: 'child',
  props:['a','b'],
  inheritAttrs:false,
  mounted(){
    //控制檯輸出:
    //child:$attrs: {c: "c"}
    console.log('child:$attrs:',this.$attrs);
  }
}
</script>

組件能夠經過在本身的子組件上使用v-bind=」$attrs」,進一步把值傳給本身的子組件。也就是說子組件會把$attrs的值看成傳入的prop處理,同時還要遵照第一點的規則。

//parent.vue
<template>
  <div>
    <child a="a" b="b" c="c"></child>
  </div>
</template>
//child.vue
<template>
  <div>
    <grand-child v-bind="$attrs" d="d"></grand-child>
  </div>
</template>
<script>
export default {
  name: 'child',
  props:['a','b'],
  inheritAttrs:false
}
</script>
//grandchild.vue
<script>
export default {
  name: 'grandchild',
  props:[],
  //props:['c'],
  inheritAttrs:false,
  mounted(){
    //控制檯輸出:
    //grandchild:$attrs: {d: "d", c: "c"}
    console.log('grandchild:$attrs:',this.$attrs);
    //若是props:['c']
    //控制檯輸出:
    //grandchild:$attrs: {d: "d"}
  },
}
</script>

vm.$listeners

類型:{ [key: string]: Function | Array } 只讀 包含了父做用域中的 (不含 .native 修飾器的) v-on 事件監聽器。它能夠經過 v-on=」$listeners」 傳入內部組件——在建立更高層次的組件時很是有用。

概括起來也是兩點:

  • vm.$listeners是組件的內置屬性,它的值是父組件(不含 .native 修飾器的) v-on 事件監聽器。
  • 組件能夠通 過在本身的子組件上使用v-on=」$listeners」,進一步把值傳給本身的子組件。若是子組件已經綁定$listener中同名的監聽器,則兩個監聽器函數會以冒泡的方式前後執行。
//parent.vue
<template>
  <div>
    <child @update="onParentUpdate"></child>
  </div>
</template>
<script>
export default {
  name: 'parent',
  components:{
    Child
  },
  methods:{
    onParentUpdate(){
      console.log('parent.vue:onParentUpdate')
    }
  }
}
</script>
//child.vue
<template>
  <div>
    <grand-child @update="onChildUpdate" v-on="$listeners"></grand-child>
  </div>
</template>
<script>
export default {
  name: 'child',
  components:{
    GrandChild
  },
  methods:{
    onChildUpdate(){
      console.log('child.vue:onChildUpdate')
    }
  }
}
</script>
//grandchild.vue
<script>
export default {
  name: 'grandchild',
  mounted(){
    //控制檯輸出:
    //grandchild:$listeners: {update: ƒ}
    console.log('grandchild:$listeners:',this.$listeners);
    //控制檯輸出:
    //child.vue:onChildUpdate
    //parent.vue:onParentUpdate
    this.$listeners.update();
  }
}
</script>

前端全棧學習交流圈:866109386,面向1-3經驗年前端開發人員,幫助突破技術瓶頸,提高思惟能力

3、組件選項 provide/inject

2.2.0 新增 若是列舉Vue組件之間的通訊方法,通常都會說經過prop,自定義事件,事件總線,還有Vuex。provide/inject提供了另外一種方法。 這對選項須要一塊兒使用,以容許一個祖先組件向其全部子孫後代注入一個依賴,不論組件層次有多深,並在起上下游關係成立的時間裏始終生效。 若是你熟悉 React,這與 React 的上下文特性(context)很類似。

不過須要注意的是,在文檔中並不建議直接用於應用程序中。

provide 和 inject 主要爲高階插件/組件庫提供用例。並不推薦直接用於應用程序代碼中。

//parent.vue
<template>
  <div>
    <child></child>
  </div>
</template>
<script>
export default {
  name: 'parent',
  provide: {
    data: 'I am parent.vue'
  },
  components:{
    Child
  }
}
</script>
//child.vue
<template>
  <div>
    <grand-child></grand-child>
  </div>
</template>
<script>
export default {
  name: 'child',
  components:{
    GrandChild
  }
}
</script>
//grandchild.vue
<script>
export default {
  name: 'grandchild',
  inject: ['data'],
  mounted(){
    //控制檯輸出:
    //grandchild:inject: I am parent.vue
    console.log('grandchild:inject:',this.data);
  }
}
</script>

前端全棧學習交流圈:866109386,面向1-3經驗年前端開發人員,幫助突破技術瓶頸,提高思惟能力

provide 選項應該是一個對象或返回一個對象的函數。該對象包含可注入其子孫的屬性。 inject 選項應該是一個字符串數組或一個對象,該對象的 key 表明了本地綁定的名稱,value 就爲provide中要取值的key。

在2.5.0+時對於inject選項爲對象時,還能夠指定from來表示源屬性,default指定默認值(若是是非原始值要使用一個工廠方法)。

const Child = {
 inject: {
  foo: {
   from: 'bar',
   default: 'foo'
   //default: () => [1, 2, 3]
  }
 }
}

4、做用域插槽 slot-scope

2.1.0 新增 在 2.5.0+,slot-scope 再也不限制在 template 元素上使用,而能夠用在插槽內的任何元素或組件上。

做用域插槽的文檔說明很詳細。下面舉個例子來展現下應用場景。

能夠看出列表頁和編輯頁對於數據的展現是同樣的,惟一的區別是在不一樣頁面對於數據有不一樣的處理邏輯。相同的數據展現這塊就可抽取成一個組件,不一樣的地方則能夠藉助做用域插槽實現。

//data-show.vue
<template>
<div>
  <ul>
    <li v-for="item in list">
      <span>{{item.title}}</span>
      <slot v-bind:item="item">
      </slot>
    </li>
  </ul>
</div>
</template>
 
//list.vue
<template>
<p>列表頁</p>
  <data-show :list="list">
    <template slot-scope="slotProps">
      <span v-if="slotProps.item.complete">✓</span>
      <span v-else>x</span>
    </template>
  </data-show>
</template>
 
//edit.vue
<template>
<p>編輯頁</p>
  <data-show :list="list">
    <template slot-scope="slotProps">
      <a v-if="slotProps.item.complete">查看</a>
      <a v-else>修改</a>
    </template>
  </data-show>
</template>

5、Vue的錯誤捕獲

全局配置errorHandler

從2.2.0起,這個鉤子也會捕獲組件生命週期鉤子裏的錯誤。 從 2.4.0 起這個鉤子也會捕獲 Vue 自定義事件處理函數內部的錯誤了。

更詳細的說明能夠查看文檔errorHandler

生命週期鉤子errorCaptured

2.5.0+新增

更詳細的說明能夠查看文檔errorCaptured

若是熟悉React的話,會發現它跟錯誤邊界(Error Boundaries)的概念很像,實際上也確實是這麼用的。

在文檔Error Handling with errorCaptured Hook就舉了一個典型的例子

Vue.component('ErrorBoundary', {
 data: () => ({ error: null }),
 errorCaptured (err, vm, info) {
  this.error = `${err.stack}\n\nfound in ${info} of component`
  return false
 },
 render (h) {
  if (this.error) {
   return h('pre', { style: { color: 'red' }}, this.error)
  }
  // ignoring edge cases for the sake of demonstration
  return this.$slots.default[0]
 }
})
<error-boundary>
 <another-component/>
</error-boundary>

須要強調的是errorCaptured並不能捕獲自身錯誤和異步錯誤(好比網絡請求,鼠標事件等產生的錯誤)。

In 2.5 we introduce the new errorCaptured hook. A component with this hook captures all errors (excluding those fired in async callbacks) from its child component tree (excluding itself).

相關文章
相關標籤/搜索