如题,我有一个List.vue
,里面包含了两个子组件,tab
和pagination
,这个List.vue
的数据是从接口得来的,从接口的来的数据分别是categories
, tabs
, active
,它们三个都是对象,我现在需要在子组件Tab.vue
中使用这个tabs
对象,应该如何将这个对象传递给子组件呢?
<template>
<tab></tab>
<p class="col-lg-12">
<table class="table table-bordered table-responsive">
<thead>
<tr>
<th>#</th>
<th>category name</th>
<th>superior belong</th>
<th>sort</th>
<th>operation</th>
</tr>
</thead>
<tbody>
<tr v-for="cat in categories">
<td>{{ cat.id }}</td>
<td>{{ cat.name }}</td>
<td>{{ cat.parent_id }}</td>
<td>{{ cat.sort_order }}</td>
<td>
<a class="btn btn-primary" v-link="{ path: '/category/edit/' }"><i class="fa fa-edit"> </i>edit</a>
<a class="btn btn-danger" v-link="{ path: '/category/delete/' }"><i class="fa fa-remove"> </i>delete</a>
</td>
</tr>
</tbody>
</table>
<pagination></pagination>
</p>
</template>
<script>
var Pagination = require('../common/Pagination.vue');
var Tab = require('../common/Tab.vue');
export default{
components:{
tab: Tab,
pagination: Pagination
},
data() {
return {
categories: [],
tabs: [
{
'name': 'Foo',
'url': '/foo'
},
{
'name': 'bar',
'url': '/bar'
}],
active: '1'
};
},
ready() {
this.$http.get('/categories').then((response) => {
console.log(response.data);
// success
this.$set('categories', response.data.categories);
this.$set('tabs', response.data.tabs);
this.$set('active', response.data.active);
}, (response) => {
// error
console.log(response);
})
}
}
</script>
在这里我已经使用了
props
,这样就可以直接使用tabs
了吗?好像不行,求各位大神解答。
<template>
<p class="col-lg-12 gap-bottom">
<ul v-for="tab in tabs" class="nav nav-tabs">
<li role="presentation"><a href="#!{{ tab.url }}">{{ tab.name }}</a></li>
</ul>
</p>
</template>
<script>
export default {
props: [
'tabs',
'active'
],
ready() {
console.log('tab ready');
console.log(this.$data);
console.log(this.tabs);
}
}
</script>
给子组件传递数据的方式不太对吧,如果想给子组件传递数据,需要使用
v-bind
动态绑定到子组件上,所以这样你在子组件的
props
中写tabs
才可以上一个答案说得对,子组件里的props只是注册这个属性,意思是告诉别人我接受这个叫做tabs的属性,并其把传过来的值放到我的原型里,但你父组件还要真的去传这个属性啊。
另外需要注意一点,父组件传过来的tabs也是响应式的,就是父组件里有变动子组件里的tabs也会跟着变
父组件向子组件传参的时候,这样使用子组件
<tab :tabs="tabs" ></tab>
,其中第一个tabs是你在子组件的props中声明的,第二个tabs是你在父组件的data中声明的。这样父组件的data中的tabs就向子组件中props中tabs传值了。我也是刚学习的。