Tomislav Tomi Nikolic
Tomislav Tomi Nikolic

Reputation: 628

Binding vue components to class name

Alright so I am trying to bind this vue components to a class name so it triggers on every element that has this class but what happens is that it only works with the first element and not with other ones

<div class="__comment_post"> 
    <textarea></textarea> 
    <input type="submit" v-on:click="submitComment" /> <!-- submit comment being only triggered on this one -->
</div>


<div class="__comment_post">
    <textarea></textarea> 
    <input type="submit" v-on:click="submitComment" />
</div>


<div class="__comment_post">
    <textarea></textarea> 
    <input type="submit" v-on:click="submitComment" />
</div>

As you can see above, I've got 3 divs with class __comment_post so naturally submitComment should be bound to all these 3 divs but what happens is that submitComment is being triggered only on the first one

var app = new Vue({

    el:".__comment_post",
    data: {
        comment: ""
    },


    methods: {
        submitComment: function() {
            console.log("Test");
        }
    }

});

Upvotes: 3

Views: 2920

Answers (2)

Vamsi Krishna
Vamsi Krishna

Reputation: 31362

The vue instance is mounted on the first found DOM element with the css selector passed to the el option. So the rest two div have no vue instances mounted on them.

So wrap your divs with a wrapper div and mount the vue instance on that wrapper

<div id="app">
<div class="__comment_post"> 
    <textarea></textarea> 
    <input type="submit" v-on:click="submitComment" /> <!-- submit comment being only triggered on this one -->
</div>


<div class="__comment_post">
    <textarea></textarea> 
    <input type="submit" v-on:click="submitComment" />
</div>


<div class="__comment_post">
    <textarea></textarea> 
    <input type="submit" v-on:click="submitComment" />
</div>

script

var app = new Vue({

    el:"#app",
    data: {
        comment: ""
    },


    methods: {
        submitComment: function() {
            console.log("Test");
        }
    }

});

Upvotes: 1

haMzox
haMzox

Reputation: 2109

Here is a little example you and others can follow in order to bind vue instance to class names.
Lets say, you would like to bind Vue to multiple existing <div class="comment"> element in HTML.

HTML:

<div class="comment" data-id="1">

<div>

<div class="comment" data-id="2">

<div>

Now, you can try the following logic/code to your example.

JS:

var comments = {
  "1": {"content": "Comment 1"},
  "2": {"content": "Comment 2"}
}

$('.comment').each(function () {
  var $el = $(this)

  var id = $el.attr('data-id')
  var data = comments[id]

  new Vue({
    el: this,
    data: data,
    template: '<div class="comment">{{ content }}<div>'
  })
})

I hope this will answer your question :)

Upvotes: 1

Related Questions