2

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
  • 1
    It makes it easier to answer a question when the problem is more evident. Here is your fiddle showing your problem in a simple, to-the-point way. jsfiddle.net/pr7h32r5/2 Now when we solve this fiddle you can apply the fix to your more complex example. That said, I don't think you can make Vue use more than on element. Commented Jun 11, 2015 at 23:45

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.