zoukankan      html  css  js  c++  java
  • vuejs动态组件和v-once指令

    场景,点击某个按钮,两个子组件交替显示
    <div id='root'>
      <child-one v-if='type==="child-one"'></child-one>
      <child-two v-if='type==="child-two"'></child-two>
      <button @click='handleBtnClick'>Button</button>
    </div>
    
    <script>
    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:{
        handleBtnClick:function(){
          this.type = (this.type === 'child-one' ? 'child-two' : 'child-one')
        }
      }
    })
    </script>
    除了上述的写法,有没有另外一种写法呢?可以通过动态组件的形式来编写这段代码
    标签component
    <div id='root'>
      <component :is='type'></component>
      <button @click='handleBtnClick'>Button</button>
    </div>
    
    <script>
    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:{
        handleBtnClick:function(){
          this.type = (this.type === 'child-one' ? 'child-two' : 'child-one')
        }
      }
    })
    </script>
    把两个子组件用<component>代替,效果一模一样,component会根据数据的变化,自动加载不同的组件,一开始进来,type的值是child-one,这个时候就会去加载child-one这个组件



    在第一个例子中,每次切换都要销毁一个组件,再创建一个组件,这个效率会比较低,如果可以把组件放到内存中效率就会有所提高
    v-once
    <div id='root'>
      <child-one v-if='type==="child-one"'></child-one>
      <child-two v-if='type==="child-two"'></child-two>
      <button @click='handleBtnClick'>Button</button>
    </div>
    
    <script>
    Vue.component('child-one',{
      template:'<div v-once>child-one</div>'
    })
    Vue.component('child-two',{
      template:'<div v-once>child-two</div>'
    })
    
    var vm = new Vue({
      el:'#root',
      data:{
        type:'child-one'
      },
      methods:{
        handleBtnClick:function(){
          this.type = (this.type === 'child-one' ? 'child-two' : 'child-one')
        }
      }
    })
    </script>




  • 相关阅读:
    PHP四种界定符
    设计模式 单例模式与工厂模式
    PHP include与require的区别
    面向对象 static abstract interface 等知识点
    gogland golang 颜色&字体 colors&font 配置文件
    什么是游戏中的帧同步
    kcp协议详解
    kcp流模式与消息模式对比
    kcp源码走读
    kcp结构体字段含义
  • 原文地址:https://www.cnblogs.com/wzndkj/p/9672407.html
Copyright © 2011-2022 走看看