温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Vue 动态组件与 v-once 指令的实现

发布时间:2020-09-04 23:55:50 来源:脚本之家 阅读:124 作者:UCCs 栏目:web开发

本文介绍了Vue 动态组件与 v-once 指令的实现,分享给大家,具体如下:

<div id="root">
  <child-one></child-one>
  <child-two></child-two>
  <button>change</button>
</div>
Vue.component('child-one', {
  template: `<div>child-one</div>`,
})
Vue.component('child-two', {
  template: `<div>child-two</div>`,
})
let vm = new Vue({
  el: '#root'
})

上面代码需实现,当点击按钮时,child-one和child-two实现toggle效果,该怎么实现呢?

<div id="root">
  <child-one v-if="type === 'child-one'"></child-one>
  <child-two v-if="type === 'child-two'"></child-two>
  <button @click="handleBtnClick">change</button>
</div>
Vue.component('child-one', {
  template: `<div>child-one</div>`,
})
Vue.component('child-two', {
  template: `<div>child-two</div>`,
})
let vm = new Vue({
  el: '#root',
  data: {
    type:'child-one'
  },
  methods: {
    handleBtnClick(){
      this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
    }
  }
})

通过上面handleBtnClick函数的实现,配合v-if指令就能实现toggle效果

动态组件

下面这段代码实现的效果和上面是一样的。

<div id="root">
  <component :is="type"></component>   //is内容的变化,会自动的加载不同的组件
  <button @click="handleBtnClick">change</button>
</div>
Vue.component('child-one', {
  template: `<div>child-one</div>`,
})
Vue.component('child-two', {
  template: `<div>child-two</div>`,
})
let vm = new Vue({
  el: '#root',
  data: {
    type:'child-one'
  },
  methods: {
    handleBtnClick(){
      this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
    }
  }
})

动态组件的意思是它会根据is里面数据的变化,会自动的加载不同的组件

v-noce指令

每次点击按钮切换的时候,Vue 底层会帮我们干什么呢?Vue 底层会判断这个child-one组件现在不用了,取而代之要用child-two组件,然后它就会把child-one组件销毁掉,在创建一个child-two组件。假设这时child-two组件要隐藏,child-one组件要显示,这个时候要把刚刚创建的child-two销毁掉,在重新创建child-one组件,也就是每一次切换的时候,底层都是要销毁一个组件,在创建一个组件,这种操作会消耗一定的性能。如果我们的组件的内容,每次都是一样的可以在上面加一个v-once,看下面代码。

Vue.component('child-one', {
  template: `<div v-once>child-one</div>`,
})
Vue.component('child-two', {
  template: `<div v-once>child-two</div>`,
})

加上v-once指令之后,有什么好处呢?当chlid-one组件第一次被渲染时,因为组件上面有一个v-once指令,所以它直接就放到内存里了,当切换的时候child-two组件第一次被渲染时,它也会被放到内存里,再次点击切换时,这时并不需要再重新创建一个child-one组件了,而是从内存里直接拿出以前的child-one组件,它的性能会更高一些。

所以在 Vue 当中,通过v-once指令,可以提高一些静态内容的展示效率

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI