美文网首页Vue
Vue-tab切换

Vue-tab切换

作者: awesome_lewis | 来源:发表于2017-08-16 11:58 被阅读64次

    CodePen预览

    • 引入CSS文件和JS文件
    <script src="https://cdn.bootcss.com/vue/2.4.0/vue.js"></script>
    <link href="https://cdn.bootcss.com/bulma/0.5.0/css/bulma.css" rel="stylesheet">
    
    • html代码
    <div id="app">
      <tabs>
        <tab name="About Us" :selected="true">
          <h1>this is the content of About Us tab.</h1>
        </tab>
        <tab name="About Our Culture">
          <h1>this is the content of About Our Culture tab.</h1>
        </tab>
        <tab name="About Our Vision">
          <h1>this is the content of about About Our Vision tab.</h1>
        </tab>
      </tabs>
    </div>
    
    • js代码
    Vue.component('tabs', {
      template: `
        <div>
          <div class="tabs">
            <ul>
              <li v-for="tab in tabs" :class="{ 'is-active': tab.isActive }">
                <a :href="tab.href" @click="selectTab(tab)">{{ tab.name }}</a>
              </li>
            </ul>
          </div>
          <div class="tabs-details">
            <slot></slot>
          </div>
        </div>
      `,
      data() {
        return {
          tabs: []
        };
      },
      created() {
        this.tabs = this.$children;
      },
      methods: {
        selectTab(selectedTab){
          this.tabs.forEach(tab => {
            tab.isActive = (tab.name == selectedTab.name);
          });
        }
      }
    });
    
    Vue.component('tab', {
      props: {
        name: { required: true },
        selected: { default: false }
      },
      template: `
        <div v-show="isActive"><slot></slot></div>
      `,
      data() {
        return {
          isActive: false
        }
      },
      computed: {
        href() {
          return '#' + this.name.toLowerCase().replace(/ /g, '-');
        }
      },
      mounted() {
        this.isActive = this.selected;
      }
    });
    
    new Vue({
      el: '#app'
    });
    

    相关文章

      网友评论

        本文标题:Vue-tab切换

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