A
A
Artem Prokhorov2021-05-13 14:43:11
Vue.js
Artem Prokhorov, 2021-05-13 14:43:11

How to pass method from parent component to child?

Vue.component('app-com', {
    props: ['user'],
    template: '<li>Имя: {{user.name}}, возраст: {{user.age}} <button v-on:click="al">Редактировать</button></li>',
});

let app = new Vue({
    el: '#app',
    data: {
        users: [
            {name: 'Коля', age: 30},
            {name: 'Вася', age: 40},
            {name: 'Петя', age: 50},
        ],
    },
    methods: {
        al: function() {alert('ok')},
    },
});

How to do this and if there are several options, which one will be the most competent?
In the child component, I specified al as a function, I just need the child component to see it.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Artem Prokhorov, 2021-05-13
@kotcich

Krch, they didn’t really understand me (I wrote everything clearly), but I decided it myself.
The problem is that when v-bind:somecode in your view (if you work in a framework) or in a regular index.php where you have markup when writing a function name with brackets, this is how v-bind:ale=al()your code will be executed immediately upon entering the page and will be executed several times if it is executed in a v-for loop.
You can fix it by simply removing the () brackets in the method binding and then everything will be fine.
If you need to pass parameters to this function, then you will need to pass them already in the component code in the js file (you can write quotes there and pass parameters too).
Here is my final code:
The code from the file where your markup will be

<div id = 'app'>
        <app-com v-for = 'user in users' :user = 'user' :ale="al"></app-com>
</div>

And the JS itself:
Vue.component('app-com', {
    props: ['user', 'ale'],
    template: '<li>Имя: {{user.name}}, возраст: {{user.age}} ' +
        '<button v-on:click="ale(user.name)">Редактировать</button></li>',
});

let app = new Vue({
    el: '#app',
    data: {
        users: [
            {name: 'Артем', age: 20},
            {name: 'Андрей', age: 22},
        ],
        postFontSize: 1,
    },
    methods: {
        al: function(value) {alert(value)},
    },
});

0
0xD34F, 2021-05-13
@0xD34F Vue.js

Just like everything else - add a description to props, use v-bind to bind the method to the component instance.
But in general, you don’t need to pass any methods here, it’s not customary to do this in vue.
In the child component, you generate an event: . Subscribe to it in the parent: . <button @click="$emit('click')"
<component @click="onClick"

V
Vladimir Korotenko, 2021-05-13
@firedragon

Don't pass it bad

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question