VueJS 如何使用组件的父方法

VueJS How to use parent method from component

我想从组件访问父组件的方法。 (不含道具)

这是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() 都不起作用。

对于 Vue.js 版本 2.2.0+,您可以使用 injectprovide 的依赖注入,如下所示:

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);
                }
            },
        }
    }
});

Fiddle: https://jsfiddle.net/haaiee/v1ahoytm/2/