现在位置: 首页 > Vue3 教程 > 正文

Vue3 v-once 指令

Vue3 内置指令 Vue3 内置指令


v-once 指令用于使元素和组件只渲染一次,后续更新会被跳过。


基本说明

v-once 指令用于将元素和组件标记为只渲染一次。在后续的重新渲染中,元素及其所有子元素会被视为静态内容跳过。这可以用于优化更新性能。

  • 期望类型: 无(不接受表达式)
  • 作用: 只渲染元素和组件一次,后续更新视为静态内容跳过。

使用场景

1、静态内容优化

当某些内容不需要更新时,使用 v-once 可以避免不必要的重渲染:

实例

<template>
  <div>
    <h1 v-once>{{ title }}</h1>
    <p>动态内容: {{ dynamicContent }}</p>
    <button @click="updateContent">更新</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: '静态标题',
      dynamicContent: '可变内容'
    }
  },
  methods: {
    updateContent() {
      this.dynamicContent = '已更新: ' + new Date().toLocaleTimeString()
    }
  }
}
</script>

Vue3 内置指令 Vue3 内置指令