<script setup> + TS + Volar = 真香
vue3.2的发布是不是到了Volar正式登上舞台的时候了?
从上面可以看出3.2增加了新的功能, 其实不但新增了功能还对性能做了极大的提升但是没看到有啥重大的更改

<script setup><style> v-bind

其中新增了两个新功能 <script setup><style> v-bind
<script setup> 是一种编译时语法糖,可在 SFC 内使用 Composition API 时极大地提升工作效率。
<style> v-bind 在 SFC 标签中启用组件状态驱动的动态 CSS 值。

<script setup>
import { ref } from 'vue'

const color = ref('red')
</script>

<template>
  <button @click="color = color === 'red' ? 'green' : 'red'">
    Color is: {{ color }}
  </button>
</template>

<style scoped>
button {
  color: v-bind(color);
}
</style>

有没有感觉又方便了好多 css里直接可以使用变量 并且语法适用于<script setup>, 并支持 JavaScript表达式(必须用引号括起来)

<script setup>
const theme = {
  color: 'red'
}
</script>

<template>
  <p>hello</p>
</template>

<style scoped>
p {
  color: v-bind('theme.color');
}
</style>

实际值将被编译为散列的 CSS 自定义属性,因此 CSS 仍然是静态的。自定义属性将通过内联样式应用于组件的根元素,并在源值更改时进行响应更新。

defineCustomElement

另外 vue3.2里面还引入了defineCustomElement一种使用 Vue 组件 API轻松创建原生自定义元素的新方法

import { defineCustomElement } from 'vue'

const MyVueElement = defineCustomElement({
  // normal Vue component options here
})

// Register the custom element.
// After registration, all `<my-vue-element>` tags
// on the page will be upgraded.
customElements.define('my-vue-element', MyVueElement)

自定义元素的主要好处是它们可以与任何框架一起使用,甚至可以在没有框架的情况下使用。这使得它们非常适合在最终消费者可能不使用相同前端堆栈的情况下分发组件,或者当您希望将最终应用程序与其使用的组件的实现细节隔离时。

Vue 支持通过defineCustomElement方法使用完全相同的Vue 组件API 创建自定义元素。该方法接受与defineComponent相同的参数,但返回一个扩展的自定义元素构造函数HTMLElement

<my-vue-element></my-vue-element>
import { defineCustomElement } from 'vue'

const MyVueElement = defineCustomElement({
  // normal Vue component options here
  props: {},
  emits: {},
  template: `...`,

  // defineCustomElement only: CSS to be injected into shadow root
  styles: [`/* inlined css */`]
})

// Register the custom element.
// After registration, all `<my-vue-element>` tags
// on the page will be upgraded.
customElements.define('my-vue-element', MyVueElement)

// You can also programmatically instantiate the element:
// (can only be done after registration)
document.body.appendChild(
  new MyVueElement({
    // initial props (optional)
  })
)

性能

1.更高效的 ref 实现(约 260% 的读取速度/约 50% 的写入速度)
2.约 40% 更快的依赖跟踪
3.内存使用量减少约 17%
4.创建普通元素 VNode 的速度提高了约 200%

新增了v-memo指令用来挤出更大性能
v-memo记住模板的子树。可用于元素和组件。该指令需要一个固定长度的依赖值数组来比较记忆。如果数组中的每个值都与上次渲染相同,则将跳过整个子树的更新。

<div v-memo="[valueA, valueB]">
  ...
</div>

当组件重新渲染时,如果valueAvalueB保持不变,<div>则将跳过此组件及其子组件的所有更新。事实上,即使是Virtual DOM VNode创建也将被跳过,因为可以重复使用子树的记忆副本。
使用这个指令的时候要注意正确使用,不然需要更新的时候也会被跳过。

用法与v-for

v-memo仅用于性能关键场景中的微优化,应该很少需要。只有在大型列表才会显现其神通。

<div v-for="item in list" :key="item.id" v-memo="[item.id === selected]">
  <p>ID: {{ item.id }} - selected: {{ item.id === selected }}</p>
  <p>...more child nodes</p>
</div>

当组件的selected状态发生变化时,即使大多数项目保持完全相同,也会创建大量 VNodev-memo这里的用法本质上是说“仅当它从非选择变为选择时才更新此项目,或者相反”。这允许每个未受影响的项目重用其先前的 VNode 并完全跳过差异。

另外还有 服务端渲染 和 效果范围 API 感兴趣的小伙伴可以去看原文 更新地址 传送门

Logo

前往低代码交流专区

更多推荐