简体   繁体   English

Vue.js - 如何使用相同的选择器处理所有元素?

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

How to create a Vue.js logic to handle all tag elements with the same class selector?如何创建一个 Vue.js 逻辑来处理具有相同类选择器的所有标签元素?

I have this simple code: http://jsfiddle.net/x2spo1qu/我有这个简单的代码: 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.但它仅适用于 HTML 中的第一个下拉列表,不适用于第二个下拉列表。

Please explain me how to do this.请解释我如何做到这一点。

From vuejs.org :来自 vuejs.org :

Vue.js uses DOM-based templating. Vue.js 使用基于 DOM 的模板。 Each Vue instance is associated with a corresponding DOM element.每个 Vue 实例都与一个相应的 DOM 元素相关联。 When a Vue instance is created, it recursively walks all child nodes of its root element while setting up the necessary data bindings.创建 Vue 实例时,它会递归遍历其根元素的所有子节点,同时设置必要的数据绑定。 After the View is compiled, it becomes reactive to data changes.视图编译后,它会响应数据更改。

you can achieve this using Vue component system follow this example :您可以使用 Vue 组件系统来实现这一点,请遵循以下示例:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM