【问题标题】:Get the calling element with vue.js使用 vue.js 获取调用元素
【发布时间】:2016-03-19 10:12:40
【问题描述】:

我想在 vue.js 中获取调用 html 元素以通过 jQuery 对其进行修改。现在我给每个元素一个类名 + 索引,然后通过 jQuery 调用它,但这看起来像一个疯狂的 hack。

我想做什么:

new Vue({
    el: "#app",
    data: {  
        testFunction : function(element) {
            $(element).doSomethingWithIt(); //do something with the calling element
        }
    }
});

这是调用元素:

<div v-on:click="testFunction(???)">Test</div> 

我可以将什么传递给函数以获取 div 元素,或者有其他方法可以实现吗?

【问题讨论】:

    标签: javascript jquery html vue.js


    【解决方案1】:

    您可以像这样从事件中获取元素:

    new Vue({
        el: "#app",
        methods: {  
            testFunction : function(event) {
                $(event.target).doSomethingWithIt();
            }
        }
    });
    

    然后:

    <div v-on:click="testFunction">Test</div>
    

    或者(如果你想传递另一个参数):

    <div v-on:click="testFunction($event)">Test</div>
    

    [demo]

    【讨论】:

    • 如果里面有另一个元素怎么办?如果单击它,目标将引用子元素。
    【解决方案2】:

    你做错了。

    new Vue({
        el: "#app",
        data: {  
            testFunction : function(element) {
                $(element).doSomethingWithIt(); //do something with the calling element
            }
        }
    });
    

    data 是您的应用的数据状态或存储。

    您需要为您的方法创建methods 对象

    new Vue({
        el: "#app",
        data: {  
    
        },
        methods: {
    
        testFunction : function(element) {
                $(element).doSomethingWithIt(); //do something with the calling element
            }
        }
    
    });
    

    【讨论】:

      【解决方案3】:

      您希望v-el 能够在其上运行 jQuery。例如:

      <div v-on:click="testFunction" v-el:my-element>Test</div>
      

      然后:

      // as noted by @vistajess
      // your function should be in the methods object
      // not the data object
      methods: {
          testFunction : function() {
              $(this.$els.myElement).doSomethingWithIt();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2020-11-07
        • 2016-09-03
        • 2015-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-20
        • 2019-09-14
        • 2018-01-26
        相关资源
        最近更新 更多