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>

 




posted @ 2018-09-19 06:51  wzndkj  阅读(1092)  评论(0编辑  收藏  举报