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

开发 前端
在项目开发中,如果业务比较复杂,特别像中台或B端功能页面都不可避免的会用到第三方组件库,产品有时会想对这些组件进行一些UI方面的定制。

[[243288]]

 一、深度作用选择器( >>> )

严格来说,这个应该是vue-loader的功能。”vue-loader”: “^12.2.0”

在项目开发中,如果业务比较复杂,特别像中台或B端功能页面都不可避免的会用到第三方组件库,产品有时会想对这些组件进行一些UI方面的定制。如果这些组件采用的是有作用域的CSS,父组件想要定制第三方组件的样式就比较麻烦了。

深度作用选择器( >>> 操作符)可以助你一臂之力。 

  1. <template>  
  2. <div>  
  3.    <h1 class="child-title">  
  4.        如果你希望 scoped 样式中的一个选择器能够作用得“更深”,例如影响子组件,你可以使用 >>> 操作   </h1>  
  5. </div>  
  6. </template>  
  7. <script>  
  8. export default {  
  9.     name: 'child',  
  10.     data() {  
  11.         return {  
  12.         }  
  13.     }  
  14.  
  15. </script>  
  16. <!-- Add "scoped" attribute to limit CSS to this component only -->  
  17. <style scoped>  
  18. .child-title {  
  19.     font-size: 12px;  
  20.  
  21. </style> 

上面的child组件中 .child-title 的作用域CSS设定字体大小为12px,现在想在父组件中定制为大小20px,颜色为红色。 

  1. <template>  
  2. <div>  
  3.    <child class="parent-custom"></child>  
  4. </div>  
  5. </template>  
  6. <script>  
  7. import Child from './child';  
  8. export default {  
  9.     name: 'parent',  
  10.     components:{  
  11.         Child  
  12.     },  
  13.     data() {  
  14.         return {  
  15.         }  
  16.     }  
  17.  
  18. </script>  
  19. <style>  
  20. .parent-custom  >>> .child-title {  
  21.     font-size:20px;  
  22.     color: red;  
  23.  
  24. </style> 

效果妥妥的。但是别高兴太早,注意到上面的style使用的是纯css语法,如果采用less语法,你可能会收到一条webpack的报错信息。 

  1. <style lang="less">  
  2. .parent-custom {  
  3.      >>> .child-title {  
  4.         font-size:20px;  
  5.         color: red;  
  6.     }  
  7.  
  8. </style>  
  9. 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 
  10.  
  11. Module build failed: Unrecognised input  
  12.  @ /src/components/parent.vue (line 22, column 6)  
  13.  near lines:  
  14.    .parent-custom {  
  15.         >>> .child-title {  
  16.            font-size:20px; 

上面的报错信息其实是less语法不认识 >>>。(less的github issue上有人提议支持>>>操作符,但本文使用的v2.7.3会有这个问题)

解决方案是采用的less的转义(scaping)和变量插值(Variable Interpolation) 

  1. <style lang="less">  
  2. @deep: ~'>>>';  
  3. .parent-custom {  
  4.      @{deep} .child-title {  
  5.         font-size:20px;  
  6.         color: red;  
  7.     }  
  8.  
  9. </style> 

对于其他的css预处理器,因为没怎么用,不妄加评论,照搬一下文档的话。

有些像 Sass 之类的预处理器无法正确解析 >>>。这种情况下你可以使用 /deep/ 操作符取而代之——这是一个 >>> 的别名,同样可以正常工作。

二、组件配置项inheritAttrs、组件实例属性$attrs和$listeners

2.4.0新增

组件配置项 inheritAttrs

我们都知道假如使用子组件时传了a,b,c三个prop,而子组件的props选项只声明了a和b,那么渲染后c将作为html自定义属性显示在子组件的根元素上。

如果不希望这样,可以设置子组件的配置项 inheritAttrs:false,根元素就会干净多了。 

  1. <script>  
  2. export default {  
  3.     name: 'child',  
  4.     props:['a','b'],  
  5.     inheritAttrs:false  
  6.  
  7. </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组件举例 

  1. //parent.vue  
  2. <template>  
  3.     <div>  
  4.         <child class="parent-custom" a="a" b="b" c="c"></child>  
  5.     </div>  
  6. </template>  
  7. //child.vue  
  8. <script>  
  9. export default {  
  10.     name: 'child',  
  11.     props:['a','b'],  
  12.     inheritAttrs:false,  
  13.     mounted(){  
  14.         //控制台输出:  
  15.         //child:$attrs: {c: "c"}  
  16.         console.log('child:$attrs:',this.$attrs);  
  17.     }  
  18.  
  19. </script> 

组件可以通过在自己的子组件上使用v-bind=”$attrs”,进一步把值传给自己的子组件。也就是说子组件会把$attrs的值当作传入的prop处理,同时还要遵守***点的规则。 

  1. //parent.vue  
  2. <template>  
  3.     <div>  
  4.         <child a="a" b="b" c="c"></child>  
  5.     </div>  
  6. </template>  
  7. //child.vue  
  8. <template>  
  9.     <div>  
  10.         <grand-child v-bind="$attrs" d="d"></grand-child>  
  11.     </div>  
  12. </template>  
  13. <script>  
  14. export default {  
  15.     name: 'child',  
  16.     props:['a','b'],  
  17.     inheritAttrs:false  
  18.  
  19. </script>  
  20. //grandchild.vue  
  21. <script>  
  22. export default {  
  23.     name: 'grandchild',  
  24.     props:[],  
  25.     //props:['c'],  
  26.     inheritAttrs:false,  
  27.     mounted(){  
  28.         //控制台输出:  
  29.         //grandchild:$attrs: {d: "d", c: "c"}  
  30.         console.log('grandchild:$attrs:',this.$attrs);  
  31.         //如果props:['c']  
  32.         //控制台输出:  
  33.         //grandchild:$attrs: {d: "d"}  
  34.     },  
  35.  
  36. </script> 

vm.$listeners

类型:{ [key: string]: Function | Array }

只读

包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on=”$listeners” 传入内部组件——在创建更高层次的组件时非常有用

归纳起来也是两点:

  1.  vm.$listeners是组件的内置属性,它的值是父组件(不含 .native 修饰器的) v-on 事件监听器。
  2.  组件可以通过在自己的子组件上使用v-on=”$listeners”,进一步把值传给自己的子组件。如果子组件已经绑定$listener中同名的监听器,则两个监听器函数会以冒泡的方式先后执行。 
  1. //parent.vue  
  2. <template>  
  3.     <div>  
  4.         <child @update="onParentUpdate"></child>  
  5.     </div>  
  6. </template>  
  7. <script>  
  8. export default {  
  9.     name: 'parent',  
  10.     components:{  
  11.         Child  
  12.     },  
  13.     methods:{  
  14.         onParentUpdate(){  
  15.             console.log('parent.vue:onParentUpdate')  
  16.         }  
  17.     }  
  18.  
  19. </script>  
  20. //child.vue  
  21. <template>  
  22.     <div>  
  23.         <grand-child @update="onChildUpdate" v-on="$listeners"></grand-child>  
  24.     </div>  
  25. </template>  
  26. <script>  
  27. export default {  
  28.     name: 'child',  
  29.     components:{  
  30.         GrandChild  
  31.     },  
  32.     methods:{  
  33.         onChildUpdate(){  
  34.             console.log('child.vue:onChildUpdate')  
  35.         }  
  36.     }  
  37.  
  38. </script>  
  39. //grandchild.vue  
  40. <script>  
  41. export default {  
  42.     name: 'grandchild',  
  43.     mounted(){  
  44.         //控制台输出:  
  45.         //grandchild:$listeners: {update: ƒ}  
  46.         console.log('grandchild:$listeners:',this.$listeners);  
  47.         //控制台输出:  
  48.         //child.vue:onChildUpdate  
  49.         //parent.vue:onParentUpdate  
  50.         this.$listeners.update();  
  51.     }  
  52.  
  53. </script> 

三、组件选项 provide/inject

    2.2.0 新增

如果列举Vue组件之间的通信方法,一般都会说通过prop,自定义事件,事件总线,还有Vuex。provide/inject提供了另一种方法。

这对选项需要一起使用,以允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效。

如果你熟悉 React,这与 React 的上下文特性(context)很相似。

不过需要注意的是,在文档中并不建议直接用于应用程序中。

provide 和 inject 主要为高阶插件/组件库提供用例。并不推荐直接用于应用程序代码中。 

  1. //parent.vue  
  2. <template>  
  3.     <div>  
  4.         <child></child>  
  5.     </div>  
  6. </template>  
  7. <script>  
  8. export default {  
  9.     name: 'parent',  
  10.     provide: {  
  11.         data: 'I am parent.vue'  
  12.     },  
  13.     components:{  
  14.         Child  
  15.     }  
  16.  
  17. </script>  
  18. //child.vue  
  19. <template>  
  20.     <div>  
  21.         <grand-child></grand-child>  
  22.     </div>  
  23. </template>  
  24. <script>  
  25. export default {  
  26.     name: 'child',  
  27.     components:{  
  28.         GrandChild  
  29.     }  
  30.  
  31. </script>  
  32. //grandchild.vue  
  33. <script>  
  34. export default {  
  35.     name: 'grandchild',  
  36.     inject: ['data'],  
  37.     mounted(){  
  38.         //控制台输出:  
  39.         //grandchild:inject: I am parent.vue  
  40.         console.log('grandchild:inject:',this.data);  
  41.     }  
  42.  
  43. </script> 

provide 选项应该是一个对象或返回一个对象的函数。该对象包含可注入其子孙的属性。

inject 选项应该是一个字符串数组或一个对象,该对象的 key 代表了本地绑定的名称,value 就为provide中要取值的key。

在2.5.0+时对于inject选项为对象时,还可以指定from来表示源属性,default指定默认值(如果是非原始值要使用一个工厂方法)。 

  1. const Child = {  
  2.   inject: {  
  3.     foo: {  
  4.       from: 'bar',  
  5.       default: 'foo'  
  6.       //default: () => [1, 2, 3]  
  7.     }  
  8.   }  

四、作用域插槽 slot-scope

2.1.0 新增

在 2.5.0+,slot-scope 不再限制在 template 元素上使用,而可以用在插槽内的任何元素或组件上。

作用域插槽的文档说明很详细。下面举个例子来展示下应用场景。

可以看出列表页和编辑页对于数据的展示是一样的,***的区别是在不同页面对于数据有不同的处理逻辑。相同的数据展示这块就可抽取成一个组件,不同的地方则可以借助作用域插槽实现。 

  1. //data-show.vue  
  2. <template>  
  3. <div>  
  4.    <ul>  
  5.         <li v-for="item in list">  
  6.             <span>{{item.title}}</span>  
  7.             <slot v-bind:item="item">  
  8.             </slot>  
  9.         </li>  
  10.     </ul>  
  11. </div>  
  12. </template>  
  13. //list.vue  
  14. <template>  
  15. <p>列表页</p>  
  16.     <data-show :list="list">  
  17.         <template slot-scope="slotProps">  
  18.             <span v-if="slotProps.item.complete"></span>  
  19.             <span v-else>x</span>  
  20.         </template>  
  21.     </data-show>  
  22. </template>  
  23. //edit.vue  
  24. <template>  
  25. <p>编辑页</p>  
  26.    <data-show :list="list">  
  27.        <template slot-scope="slotProps">  
  28.            <a v-if="slotProps.item.complete">查看</a>  
  29.            <a v-else>修改</a>  
  30.        </template>  
  31.    </data-show>  
  32. </template> 

五、Vue的错误捕获

全局配置errorHandler

从2.2.0起,这个钩子也会捕获组件生命周期钩子里的错误。

从 2.4.0 起这个钩子也会捕获 Vue 自定义事件处理函数内部的错误了。

更详细的说明可以查看文档errorHandler

生命周期钩子errorCaptured

2.5.0+新增

更详细的说明可以查看文档errorCaptured

如果熟悉React的话,会发现它跟错误边界(Error Boundaries)的概念很像,实际上也确实是这么用的。

在文档Error Handling with errorCaptured Hook就举了一个典型的例子 

  1. Vue.component('ErrorBoundary', {  
  2.   data: () => ({ error: null }),  
  3.   errorCaptured (err, vm, info) {  
  4.     this.error = `${err.stack}\n\nfound in ${info} of component`  
  5.     return false  
  6.   },  
  7.   render (h) {  
  8.     if (this.error) {  
  9.       return h('pre', { style: { color: 'red' }}, this.error)  
  10.     }  
  11.     // ignoring edge cases for the sake of demonstration  
  12.     return this.$slots.default[0]  
  13.   }  
  14. })  
  1. <error-boundary>  
  2.   <another-component/>  
  3. </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). 

责任编辑:庞桂玉 来源: 前端大全
相关推荐

2021-04-23 07:51:56

CSS Container Q Chrome

2011-07-19 18:11:09

iPhone 开发

2017-05-23 14:33:46

简历求职前端开发

2009-07-07 17:34:15

collectionJDK5.0

2012-12-24 14:51:02

iOS

2009-06-16 13:29:56

JBoss事务

2022-05-24 12:50:58

Pandas索引代码

2013-03-29 09:03:59

iOS实用小代码iOS开发

2011-03-16 10:40:42

JavaEEJ2EE

2023-11-13 07:54:54

.NET Core开源框架

2014-03-19 15:41:21

编程语言编程规则

2014-08-08 09:14:43

Linux浏览器

2014-08-26 10:03:45

Oracle 12c新

2013-07-24 09:32:13

Android项目

2010-03-25 13:59:52

Python API

2016-11-16 21:18:42

android日志

2018-07-30 08:41:48

VueReact区别

2011-06-24 14:46:23

Qt

2011-06-16 14:28:08

Qt Symbian 文件

2010-08-17 10:16:37

DIV样式
点赞
收藏

51CTO技术栈公众号