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>

 





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM