【问题标题】:How does Vue.js select `v-on:click` selector?Vue.js 如何选择 `v-on:click` 选择器?
【发布时间】:2017-08-15 01:58:57
【问题描述】:

我试图复制 Vue.js 只是为了学习。

用非常基本的术语来说,我可以这样做:

<button v-on-click="reverseMessage">Reverse Message</button>
var element = document.querySelectorAll('[v-on-click]')[0]

但是,我很想知道他们如何选择v-on:click。

当我尝试document.querySelectorAll('[v-on:click]') 时,我收到此错误:

未捕获的 DOMException:无法在“文档”上执行“querySelectorAll”:“[v-on:click]”不是有效的选择器。

【问题讨论】:

  • 检查您的元素并查看生成的内容。你也可以使用 Vue.js Chrome 扩展。事实是事件被注册了,在 vue.js 渲染根之后你不会看到任何 v-on:click 。

标签: javascript vue.js


【解决方案1】:

查看repository on Github for Vue,看起来他们首先获取了一个元素的所有属性。然后他们针对每个属性测试正则表达式const onRE = /^@|^v-on:/,如果匹配,他们从属性名称中删除v-on: 或@ 前缀(通过name.replace(onRE, ''))留下要处理的事件名称。然后他们处理事件。

这是他们方法的简化示例:

const vonReg = /^@|^v-on:/;
let attributes = document.getElementById("foo").attributes;

let names = [];
for (let i = 0; i < attributes.length; i++) {
  names.push(attributes[i].nodeName);
}

names.forEach((name) => {
  if (vonReg.test(name)) {
    let eventName = name.replace(vonReg, '');
    console.log('We need to handle this event: ' + eventName);
  }
})
&lt;div id="foo" v-on:click="test"&gt;&lt;/div&gt;

如果要使用querySelectorAll,this post 说明需要对冒号进行转义。在您的情况下,它看起来像这样:

document.querySelectorAll('[v-on\\3A click]')

【讨论】:

    猜你喜欢
    • 2016-06-14
    • 2019-06-05
    • 2017-12-31
    • 2017-12-18
    • 2017-07-05
    • 2019-07-01
    • 2017-09-10
    • 1970-01-01
    • 2017-10-09
    相关资源
    最近更新 更多