从组件中我想访问父方法。 (没有道具)
这是HTML:
<div id="el">
<user v-for="user in users" :item="user"></user>
</div>
这是Vue代码:
var usersData = [
{ id:1, firstname:'John', lastname: 'Doe' },
{ id:2, firstname:'Martin', lastname: 'Bust' }
];
var vm = new Vue({
el: '#el',
data: { users: usersData },
methods: {
getFullName: function (user) {
return user.id + '. ' + user.firstname + ' ' + user.lastname;
}
},
components: {
user: {
template: '<span>{{ fullName }}</span>',
props: ['item'],
computed: {
fullName: function(){
return this.$parent.getFullName(this.item);
}
},
}
}
});
VueJS版本:2.0.2
this.$parent.$options.methods.getFullName()
和this.$parent.methods.getFullName()
都无效。
答案 0 :(得分:2)
对于Vue.js 2.2.0+版,您可以使用依赖注入inject
和provide
,如下所示:
HTML:
<div id="el">
<user v-for="user in users" :item="user"></user>
</div>
JavaScript的:
var usersData = [
{ id:1, firstname:'John', lastname: 'Doe' },
{ id:2, firstname:'Martin', lastname: 'Bust' }
];
var vm = new Vue({
el: '#el',
data: { users: usersData },
methods: {
getFullName: function (user) {
return user.id + '. ' + user.firstname + ' ' + user.lastname;
}
},
provide: function () {
return {
getFullName: this.getFullName
}
},
components: {
user: {
template: '<span>{{ fullName }}</span>',
inject: ['getFullName'],
props: ['item'],
computed: {
fullName: function(){
return this.getFullName(this.item);
}
},
}
}
});