简体   繁体   English

如何从Vue.js中的子组件访问父方法?

[英]How can I access a parent method from child component in Vue.js?

I am trying to call a parent/root level method on a child component in Vue.js, but I keep getting a message saying TypeError: this.addStatusClass is not a function . 我试图在Vue.js中的子组件上调用父/根级别方法,但我不断收到一条消息说TypeError: this.addStatusClass is not a function

Vue.component('spmodal', {
    props: ['addStatusClass'],
    created: function() {
        this.getEnvironments();
    },
    methods: {
        getEnvironments: function() {
            this.addStatusClass('test');
        }
    }
});

new Vue({
    el: '#app',
    methods: {
        addStatusClass(data) {
          console.log(data);
        }
    }
});

Here is a full JSBIN example: http://jsbin.com/tomorozonu/edit?js,console,output 这是一个完整的JSBIN示例: http ://jsbin.com/tomorozonu/edit?js,console,output

If I call this.$parent.addStatusClass('test'); 如果我这样称this.$parent.addStatusClass('test'); it works fine, but based on the Vue.js documentation, this is bad practice and I should be using props which is not working. 它工作正常,但基于Vue.js文档,这是不好的做法,我应该使用不起作用的道具。

指定prop本身没有任何作用,你必须实际从父对象传递一些东西 - 在本例中是函数。

<spmodal :add-status-class="addStatusClass"></spmodal>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM