目录

动态组件与 v-once 指令

# 动态组件与 v-once 指令

# 动态组件

<div id="root">
	<component :is="type"></component> <!--其效果如同下面两行被注释的代码-->
	<!-- <child-one v-if="type === 'child-one'"></child-one>
	    <child-two v-if="type === 'child-two'"></child-two> -->
	<button @click="handleClick">change</button>
</div>
<script type="text/javascript">
    Vue.component('child-one', {
        template: '<div>child-one</div>'
    })
    Vue.component('child-two', {
        template: '<div>child-two</div>'
    })

    var vm = new Vue({
        el: '#root',
        data: {
            type: 'child-one'
        },
        methods: {
            handleClick() {
                this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
            }
        }
    })
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

上面代码中,点击按钮在两个组件间切换,可使用<component>标签并绑定:is为动态组件名。

# 动态组件 demo

See the Pen 动态组件 by xugaoyi (@xugaoyi) on CodePen.

# v-once 指令

  • 不需要表达式

  • 详细

    只渲染元素和组件一次。随后的重新渲染,元素/组件及其所有的子节点将被视为静态内容并跳过。这可以用于优化更新性能。

    <!-- 单个元素 -->
    <span v-once>This will never change: {{msg}}</span>
    <!-- 有子元素 -->
    <div v-once>
      <h1>comment</h1>
      <p>{{msg}}</p>
    </div>
    <!-- 组件 -->
    <my-component v-once :comment="msg"></my-component>
    <!-- `v-for` 指令-->
    <ul>
      <li v-for="i in list" v-once>{{i}}</li>
    </ul>
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
  • 参考

# 通过 v-once 创建低开销的静态组件

渲染普通的 HTML 元素在 Vue 中是非常快速的,但有的时候你可能有一个组件,这个组件包含了大量静态内容。在这种情况下,你可以在根元素上添加 v-once attribute 以确保这些内容只计算一次然后缓存起来,就像这样:

Vue.component('terms-of-service', {
  template: `
    <div v-once>
      <h1>Terms of Service</h1>
      ... a lot of static content ...
    </div>
  `
})
1
2
3
4
5
6
7
8

警告

再说一次,试着不要过度使用这个模式。当你需要渲染大量静态内容时,极少数的情况下它会给你带来便利,除非你非常留意渲染变慢了,不然它完全是没有必要的——再加上它在后期会带来很多困惑。例如,设想另一个开发者并不熟悉 v-once 或漏看了它在模板中,他们可能会花很多个小时去找出模板为什么无法正确更新。

上次更新: 2023/07/11, 15:43:07
最近更新
01
基本知识
07-18
02
卷积神经网络识别图像
07-18
03
损失函数
07-18
更多文章>