【发布时间】:2018-02-15 15:36:07
【问题描述】:
如何使用 VueJS 打开第一个选项卡?我已经制作了两个组件,但我不知道如何自动打开第一个选项卡。这是我尝试过的,但它不起作用:
在安装时我执行 console.log(this.tabs) 仅返回 0 但在我执行此操作之前 this.tabs = this.$children
Tabs.vue
<template>
<div>
<div class="tabs-header">
<ul>
<li v-for="tab in tabs" :key="tab.id" :class="{'is-active' : tab.isActive}">
<a :href="tab.href" @click="selectTab(tab)">{{ tab.name }}</a>
</li>
</ul>
</div>
<div class="content">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
name: "Tabs",
data: function(){
return { tabs: null };
},
created: function() {
this.tabs = this.$children;
//this.tabs[0].isActive = true;
},
methods: {
selectTab (selectedTab){
this.tabs.forEach(tab => {
tab.isActive = (tab.href == selectedTab.href);
});
}
}
}
</script>
这是我的第二个组件 $children Tab.vue
<template>
<div v-show="isActive">
<slot></slot>
</div>
</template>
<script>
export default {
name: "Tabs",
props: {
name: { require: true },
selected: { default: false }
},
data() {
return { isActive: false }
},
computed: {
href() {
return '#' + this.name.toLowerCase().replace(/ /g,'-');
}
},
mounted() {
this.isActive = this.selected;
},
methods: {
select(){
this.isActive = true;
}
}
}
</script>
这行不行:
//this.tabs[0].isActive = true;
【问题讨论】:
-
你的组件有子组件吗?你能记录下这个$children 吗?
-
[ob:观察者]
-
我没有看到您的第一个组件调用任何其他“子”组件。我认为您的代码中有很多错误。也许你应该发布一个 jsFidlle。
-
这里 this.tabs = this.$children;在创建的方法中
-
查看文档,了解如何注册组件vuejs.org/v2/guide/components.html。目前,您没有这样做,所以 this.$children 不包含任何内容。 this.tabs 指的是您的数据,而不是组件。我真的认为您应该从头开始阅读文档。只需几个小时即可了解该框架的工作原理。
标签: javascript vue.js tabs components