首页 > 语言 > JavaScript > 正文

vue动态子组件的两种实现方式

2024-05-06 15:35:11
字体:
来源:转载
供稿:网友

文章目录

方式一:局部注册所需组件 使用缓存 方式二:动态注册组件实现

让多个组件使用同一个挂载点,并动态切换,这就是动态组件。

通过使用保留的 <component>元素,动态地绑定到它的 is 特性,可以实现动态组件。

方式一:局部注册所需组件

<div id="example"> <button @click="change">切换页面</button> <component :is="currentView"></component></div><script>var home = {template:'<div>我是主页</div>'};var post = {template:'<div>我是提交页</div>'};var archive = {template:'<div>我是存档页</div>'};new Vue({ el: '#example', components: {  home,  post,  archive, }, data:{  index:0,  arr:['home','post','archive'], }, computed:{  currentView(){    return this.arr[this.index];  } }, methods:{  change(){   this.index = (++this.index)%3;  } }})</script>

使用<keep-alive>缓存

<keep-alive> 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。和 <transition>相似,<keep-alive> 是一个抽象组件:它自身不会渲染一个 DOM 元素,也不会出现在父组件链中。

基本用法:

<div id="example"> <button @click="change">切换页面</button> <keep-alive>  <component :is="currentView"></component>  </keep-alive></div>

条件判断

如果有多个条件性的子元素,<keep-alive> 要求同时只有一个子元素被渲染:

<div id="example"> <button @click="change">切换页面</button> <keep-alive>  <home v-if="index===0"></home>  <posts v-else-if="index===1"></posts>  <archive v-else></archive>  </keep-alive></div><script>new Vue({ el: '#example', components:{  home:{template:`<div>我是主页</div>`},  posts:{template:`<div>我是提交页</div>`},  archive:{template:`<div>我是存档页</div>`}, }, data:{  index:0, }, methods:{  change(){   let len = Object.keys(this.$options.components).length;   this.index = (++this.index)%len;  } }})</script>

activated 和 deactivated

activated 和 deactivated 在 <keep-alive> 树内的所有嵌套组件中触发:

<div id="example"> <button @click="change">切换页面</button> <keep-alive>  <component :is="currentView" @pass-data="getData"></component>  </keep-alive> <p>{{msg}}</p></div><script>new Vue({ el: '#example', data:{  index:0,  msg:'',    arr:[   {     template:`<div>我是主页</div>`,    activated(){     this.$emit('pass-data','主页被添加');    },    deactivated(){     this.$emit('pass-data','主页被移除');    },       },   {template:`<div>我是提交页</div>`},   {template:`<div>我是存档页</div>`}  ], }, computed:{  currentView(){    return this.arr[this.index];  } }, methods:{  change(){   var len = this.arr.length;   this.index = (++this.index)% len;  },  getData(value){   this.msg = value;   setTimeout(()=>{    this.msg = '';   },500)  } }})</script>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选