Vue 组件:如何将数据从父级传递给子级
Posted
技术标签:
【中文标题】Vue 组件:如何将数据从父级传递给子级【英文标题】:Vue Component: how to pass data from parent to child 【发布时间】:2017-06-24 12:21:24 【问题描述】:如何从我的医生组件中访问医生属性?
Vue.component('specialists',
template: `
<div>
<div class="list-group-item title">
» name
</div>
<doctor class="list-group-item" v-for="doctor in doctors">
<a href="#" class="list-group-item-heading">
doctor.full_name
</a>
</doctor>
</div>
`,
props:
name:
default: '',
,
,
data: function()
return
algoliaClient: null,
algoliaIndex: null,
doctors: [],
;
,
created: function()
this.algoliaClient = this.$parent.algoliaClient;
this.algoliaIndex = this.algoliaClient.initIndex('medical_doctors');
,
mounted: function()
this.getDoctors();
,
methods:
getDoctors: function()
this.search(this.name);
,
search: function(input)
var _this = this;
this.algoliaIndex.search(this.name, function(err, hits)
_this.setDoctors(hits.hits);
);
,
setDoctors: function(data)
this.doctors = data;
,
,
);
// my doctor component
Vue.component('doctor',
template: `
<div><slot></slot></div>
`,
data: function()
return
doctor: null, // here. how can i pass value to it?
;
,
);
如何从我的专家组件中访问医生属性?
我尝试从专家组件访问this.$children
,但孩子为空
【问题讨论】:
vuejs update parent data from child component的可能重复 @Saurabh 那个问题是“从孩子到父母”,这个问题是“从父母到孩子” 【参考方案1】:我会尝试这样的:
Vue.component('specialists',
template: `
<div>
<div class="list-group-item title">
» name
</div>
<doctor class="list-group-item" v-for="doctor in doctors" :doctor="doctor">
<a href="#" class="list-group-item-heading">
doctor.full_name
</a>
</doctor>
</div>
`,
props:
name:
default: '',
,
,
data: function()
return
algoliaClient: null,
algoliaIndex: null,
doctors: [],
;
,
created: function()
this.algoliaClient = this.$parent.algoliaClient;
this.algoliaIndex = this.algoliaClient.initIndex('medical_doctors');
,
mounted: function()
this.getDoctors();
,
methods:
getDoctors: function()
this.search(this.name);
,
search: function(input)
var _this = this;
this.algoliaIndex.search(this.name, function(err, hits)
_this.setDoctors(hits.hits);
);
,
setDoctors: function(data)
this.doctors = data;
,
,
);
// my doctor component
Vue.component('doctor',
template: `
<div><slot></slot></div>
`,
props:
doctor:
default: '',
);
在父级的for循环中传递:doctor="doctor"
并将医生添加到子组件中的道具
props:
doctor:
default: '',
,
,
【讨论】:
以上是关于Vue 组件:如何将数据从父级传递给子级的主要内容,如果未能解决你的问题,请参考以下文章
使用 XLPagerTabStrip 将数据从父级传递给子级