2

I'm trying to replicate Vue.js just for learning purposes.

In very basic terms I can do this:

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

But, I'm interested to know how they select v-on:click.

When I try document.querySelectorAll('[v-on:click]') I get this error:

Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': '[v-on:click]' is not a valid selector.

1
  • Inspect your element and look what is generated. You can also use Vue.js Chrome extension. The fact is that events are registered and you won't see any v-on:click after vue.js render the root. Commented Aug 14, 2017 at 17:22

1 Answer 1

1

Looking at the repository on Github for Vue, it looks like they first get all of the attributes for an element. Then they test a regex const onRE = /^@|^v-on:/ against each attribute, and if it matches, they remove the v-on: or @ prefix from the attribute name (via name.replace(onRE, '')) leaving the name of the event to handle. Then they handle the event.

Here's a simplified example of their method:

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);
  }
})
<div id="foo" v-on:click="test"></div>


If you want to use querySelectorAll, this post explains that you need to escape the colon. In your case it would look like this:

document.querySelectorAll('[v-on\\3A click]')
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.