Vue.js - How to handle all elements with the same selector?

3.4k views Asked by At

How to create a Vue.js logic to handle all tag elements with the same class selector?

I have this simple code: http://jsfiddle.net/x2spo1qu/

var dropdown = new Vue({
  el: '.dropdown',
  data: {
    is_open : false
  },
  methods: {
    onClick: function (event) {
      // # toggle the dropdown open/closed state
      // ---
      this.is_open = ! this.is_open;
    },
    mouseLeave: function (event) {
      // # set show of dropdown to false
      // ----
      this.is_open = false;
    }
  }
});

But it only works for the first dropdown in the HTML and does not work for the second.

Please explain me how to do this.

1

There are 1 answers

0
Dinoel Vokiniv On BEST ANSWER

From vuejs.org :

Vue.js uses DOM-based templating. Each Vue instance is associated with a corresponding DOM element. When a Vue instance is created, it recursively walks all child nodes of its root element while setting up the necessary data bindings. After the View is compiled, it becomes reactive to data changes.

you can achieve this using Vue component system follow this example :

var bs3_dropdown = Vue.extend
({
    props: ['name'],
    replace: true,

    template: '<li class="dropdown" v-class="open : is_open" v-on="mouseleave : mouseLeave"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" v-on="click : onClick">{{ name }} <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <content></content> </ul> </li>',

    data: function () {
        return  {
            is_open: false,
        }
    },

    methods : {
        onClick : function(event) {
            // # toggle the dropdown open/closed state
            // ---
            this.is_open = ! this.is_open;
        },
        mouseLeave : function(event) {
            // # set show of dropdown to false
            // ----
            this.is_open = false;
        }
    },

    created: function () {
        console.log('An instance of MyComponent has been created!')
    }
});

Vue.component('bs3-dropdown', bs3_dropdown);