分享Vue开发实用技巧 slots语法

分享最近学习到的实用Vue开发技巧,简单高效的代码,让代码看起来更加优雅~

slots新语法

slots新语法向vue3.0看齐。

❝使用带有“#”的新命名插槽缩写语法,在Vue 2.6.0+中可用?❞
图片[1]-分享Vue开发实用技巧 slots语法-一一网
下图举出一个简单的网页布局例子
图片[2]-分享Vue开发实用技巧 slots语法-一一网
构建插槽与构建组件没有什么不同。本质上,插槽是具有超强功能的组件,让我们细分一下上面的布局,组件的外观如下:

<!-- TidbitPage.vue -->
<template>
  <article-layout>

    <template #articleHeader>
      <h1>I am the header</h1>
    </template>

    <template #articleContent>
      <p>I am the content</p>
    </template>

    <template #articleFooter>
      <footer>I am the footer</footer>
    </template>

    <template #side>
      <aside>I am the side stuff</aside>
    </template>

    <template #banner>
      <div>I am the banner</div>
    </template>

  </article-layout>
<template>
复制代码

动态指令参数

指令参数现在可以接受动态JavaScript表达式 动态参数值应该是字符串,但允许null作为一个明确指示应该删除绑定的特殊值,那将会很方便。任何其他非字符串值都可能出错,并会触发警告。(仅适用于v-bind和v-on)

<div v-bind:[attr]="attributeName"></div>
//简写
<div :[attr]="attributeName"></div>
复制代码

这里的 attributeName 会被作为一个JavaScript表达式进行动态求值,求得的值将会作为最终的参数来使用。例如,如果你的 Vue 实例有一个 data 属性 attributeName,其值为 href,那么这个绑定将等价于 v-bind:href

同样地,你可以使用动态参数为一个动态的事件名绑定处理函数:

<button v-on:[eventName]="handler"></button>
//简写
<button @[eventName]="handler"></button>
复制代码

当 eventName 的值为 focus 时,v-on:[eventName] 将等价于v-on:focus。
同样可以适用于插槽绑定:

<my-component>
<template v-slot:[slotName]>
Dynamic slot name
</template>
</my-component>
//简写
<foo>
<template #[name]>
Default slot
</template>
</foo>
复制代码

动态参数预期会求出一个字符串,异常情况下值为 null。这个特殊的 null 值可以被显性地用于移除绑定。任何其它非字符串类型的值都将会触发一个警告。

<!-- 这会触发一个编译警告 且 无效 -->
<a v-bind:['foo' + bar]="value"> ... </a>
复制代码

变通的办法是使用没有空格或引号的表达式,或用计算属性替代这种复杂表达式。
前端路漫漫其修远兮,吾将上下而求索,一起加油,学习前端吧:stuck_out_tongue_closed_eyes:~

欢迎留言讨论~

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享