运行后效果如下:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Vue.js小demo</title>
  <style>
  h3{
    margin-top: 10px;
  }
  #content{
    width: 400px;
    margin: 30px auto;
    background: #eee;
    padding:10px;
    overflow: hidden;
  }
  .nav{
    width: 100%;
    height: 24px;
    list-style: none;
  }
  .nav li a{
    width: 30%;
    float: left;
  }
  .tab-con{
    min-height: 200px;
    margin-top: 10px;
    width: 90%;
    border-radius: 4px;
    background: #cfcfcf;
    margin:0 auto;
    padding:10px;
  }
  </style>
</head>
<body> 
<template id="temp-tab01">
    <div>this is tab01</div>
</template>
<template id="temp-tab02">
    <div>this is tab02</div>
</template>
<template id="temp-tab03">
    <div>this is tab03</div>
</template>
<div id="content">
    <h3>动态组件</h3>
    <!-- 导航栏 -->
    <ul class="nav">
        <li><a href="javascript:void(0);" @click="toggleTabs(tab01Text)">{{tab01Text}}</a></li>
        <li><a href="javascript:void(0);" @click="toggleTabs(tab02Text)">{{tab02Text}}</a></li>
        <li><a href="javascript:void(0);" @click="toggleTabs(tab03Text)">{{tab03Text}}</a></li>
    </ul>
     <!-- 点击导航后要切换的内容 -->
     <div class="tab-con">
         <component :is="currentView" keep-alive></component>
     </div>
</div>
</body>
<script src="https://cdn.bootcss.com/vue/2.2.6/vue.js"></script>
<script>
//扩展组件tab01
var tab01=Vue.extend({
    template:"#temp-tab01"
});
var tab02=Vue.extend({
    template:"#temp-tab02"
});
var tab03=Vue.extend({
    template:"#temp-tab03"
});

var dr01=new Vue({
    el:"#content",
    data:{
        tab01Text:"tab01",
        tab02Text:"tab02",
        tab03Text:"tab03",
        currentView:'tab01'//默认选中的导航栏
    },
    //局部注册组件
    components:{
        tab01:tab01,
        tab02:tab02,
        tab03:tab03
    },
    methods:{
        //绑定tab的切换事件
        toggleTabs:function(tabText){
            this.currentView=tabText;
        }
    }
});
</script>
</html>


Logo

前往低代码交流专区

更多推荐