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>




  • 相关阅读:
    读《编写可维护的JavaScript》第七章总结
    读《编写可维护的JavaScript》第六章总结
    最新Blog
    cnUVA情况
    Casio普通计算器编程
    大家AK杯 灰天飞雁NOIP模拟赛题解/数据/标程
    Pascal <-> C/C++ 转换简明教程
    [互动][扫盲]信息学奥林匹克竞赛是什么
    以后这个博客可能不会用啦 请到新地址...
    算法专题训练 搜索a-T3 Ni骑士(ni)
  • 原文地址:https://www.cnblogs.com/wzndkj/p/9672407.html
Copyright © 2011-2022 走看看