Vuejs在点击时显示标签内容

时间:2017-09-28 08:13:44

标签: javascript vue.js

我的vuejs代码有问题,我想在每次点击标签时显示具体内容。

到目前为止,这是我的代码。

<template>
  <nav class="horizontal top-border block-section">
    <div class="col-md-20" id="tabs">
       <a href="#" id="overview" class="col-md-2" @click="active">Overview</a>
       <a href="#" id="aboutcompany" class="col-md-2" @click="active">About Company</a>
  </nav>

    <div id="over" class="show">
        <overview></overview>
    </div>
    <div id="about" class="hide">
        <about-company></about-company>
    </div>

</template>

<script>
import Overview from './Overview'
import AboutCompany from './AboutCompany'

export default {
  components: {
  Overview,
  AboutCompany
},
methods: {
  active(e) {
     e.target.id.addClass('show');
  }
}
}
</script>

一旦我点击带有id =“aboutcompany”的href,id =“about”的div应该有一个“show”类,并为id =“overview”的div添加“hide”类

2 个答案:

答案 0 :(得分:3)

你可以更多地利用vuejs可以提供的东西:

<template>
  <nav class="horizontal top-border block-section">
    <div class="col-md-20" id="tabs">
      <a href="#" v-for="tab in tabs" @click.prevent="setActiveTabName(tab.name)">
        {{ tab.displayName }}
      </a>
  </nav>

  <div v-if="displayContents(activeTabName, 'overview')">
      <overview></overview>
  </div>
  <div v-if="displayContents(activeTabName, 'about')">
      <about-company></about-company>
  </div>
</template>

<script>
import Overview from './Overview'
import AboutCompany from './AboutCompany'

export default {
  components: {
  Overview,
  AboutCompany
  },
  data() {
    return {
      // List here all available tabs
      tabs: [
        {
          name: 'overview',
          displayName: 'Company Overview',
        },
        {
          name: 'about',
          displayName: 'About us',
        }
      ],
      activeTabName: null,
    };
  },
  mounted() {
    // The currently active tab, init as the 1st item in the tabs array
    this.activeTabName = this.tabs[0].name;
  },
  methods: {
    setActiveTabName(name) {
      this.activeTabName = name;
    },
    displayContents(name) {
      return this.activeTabName === name;
    },
  },
}
</script>

答案 1 :(得分:0)

您可以使用data变量来实现这一目标,而无需使用单独的function来电。

  <nav class="horizontal top-border block-section">
    <div class="col-md-20" id="tabs">
       <a href="#" id="overview" class="col-md-2" @click="activeTab = 'OVER'">Overview</a>
       <a href="#" id="aboutcompany" class="col-md-2" @click="activeTab = 'ABOUT'">About Company</a>
  </nav>

    <div id="over" class="{show : activeTab == 'OVER', hide : activeTab != 'OVER'}">
        <overview></overview>
    </div>
    <div id="about" class="{show : activeTab == 'ABOUT', hide : activeTab != 'ABOUT'}">
        <about-company></about-company>
    </div>

然后只需在数据对象中定义activeTab

data: function () {
  return {
    activeTab: "OVER"
  }
}