美文网首页
动态组件

动态组件

作者: 温梦丽 | 来源:发表于2018-08-28 17:06 被阅读0次

官网说可以通过vue的<component>元素加一个特殊的is特性来实现。
那is属性啥勒?
当我们写好的组件直接放到ul里会导致浏览器无法正常解析。因为ul里只能放li标签。

正确:

<ul>
<li></li>
</ul>

错误:

<ul>
<your-component>
</ul>

要达到我们的目的,就要使用is特性像下面这样

<ul>
<li :is="your-component"></li>
</ul>

哈哈is特性介绍到这,切回正题!
is特性怎么实现动态组件?
假设有一个tab选项卡,点击不同的选项显示不同的组件。这时候就要用is特性动态选择不同的组件了。

<template>
  <div id="app">
    <div class="container">
    <ul class="tab-wrap">
      <li v-for="tab in tabs"
          class="tab"
          @click="currentTab=tab"
      >{{tab}}</li>
    </ul>
    <div class="content">
     <component :is="currentComponent"> </component>
    </div>
    </div>
    <router-view/>
  </div>
</template>

<script>
  import  Respond from './components/input'
  import  Camel from './components/camel'
  import Cattle from './components/cattle'
  import Sheep from './components/sheep'
export default {
  name: 'App',
  data(){
    return{
      tabs:['骆驼','牛','羊'],
      currentTab:'骆驼'
    }
  },
  computed:{
    currentComponent:function(){
    if(this.currentTab=='骆驼'){
      return 'Camel';
    }else if(this.currentTab=='牛'){
      return  'Cattle'
    }else{
      return 'Sheep'
    }
    }
  },
  components:{
    Respond,
    Camel,
    Cattle,
    Sheep
  }
}
</script>

效果:

image.png image.png

相关文章

网友评论

      本文标题:动态组件

      本文链接:https://www.haomeiwen.com/subject/ukfsvftx.html