Answer the question
In order to leave comments, you need to log in
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')},
},
});
Answer the question
In order to leave comments, you need to log in
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>
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)},
},
});
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"
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question