A
A
Andrew2018-05-28 12:17:31
Vue.js
Andrew, 2018-05-28 12:17:31

How to add an event handler to a group of elements?

Hello

<div id = "content" class = "container">
            <brick-item
                v-for="item in itemList"
                v-bind:brick="item"
                v-bind:key="item.id"
                v-bind:id="item.id"
                v-bind:class="item.colorClass"
                v-on:click="greet"> 
            </brick-item>
            <div id = "98" class = "brick empty" v-on:click="greet"> </div>
            <div id = "99" class = "brick empty" v-on:click="greet"> </div>
        </div>

var Bricks = [];
            for (var i = 0; i < 98; i++) {
                Bricks[i] = {id: i, text: 'none', colorClass: 'empty'};
            }

            Vue.component('brick-item', {
                props: ['brick'],
                template: '<div class = "brick">{{ brick.text }}</div>'
            });

            var vm = new Vue({
                el: '#content',
                data: {
                    itemList: Bricks
                },
                greet: function () {
                    alert('Привет!');
                }
            }
            });

On divs with id 98 and 99 click works on brick-item elements there is no handler when I do this
template: '<div class = "brick"  v-on:click="greet">{{ brick.text }}</div>'

throws a reactivity error

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Proskurin, 2018-05-28
@AndrewHaze

https://jsfiddle.net/sxj4h3be/
1) Methods must be in the methods property of the object
2) v-on: listens to the component's own events, which are called via $emit. To listen to native, you need to add .native to get v-on:click.native="greet"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question