8

I'm new to Vue and have a few questions on it. But I think the issue I am running is the one I have no idea how to solve it:

I have a few <div class="foo"> in my code. I want to interact with these <div>s using a Vue instance. I had the idea to use something like:

var app = new Vue({
  el: 'div.foo',
  data: {
    message: 'bar'
  }
})

Therefore, all the div.foo elements would be manageable by app. But how can I get EXACTLY the element I'm working with?

Let's say in JQuery we have this...

$("div.foo").click(function() {
    console.log($(this));
})

The code will work for every div.foo, but the print will show just the clicked element.

3
  • I don't think this approach is not something you want to do, and it's not something that's recommended.Why simply not assign id to div and mount vue instance to that div, and inside instance you can create different components which would have their own state ? Pro tip: try to simply forgot everything about jQuery when you are working with VueJS ;) Commented Mar 22, 2017 at 21:05
  • Because I would have like 6 or 7 vue instances doing the same thing. What do you recommend for something like this? Commented Mar 22, 2017 at 21:06
  • It's hard to say because I don't know what you are exactly building, but I'd go with one main instance and component/s that represtent div.foo state. Commented Mar 22, 2017 at 21:15

2 Answers 2

26

You can't do what you are suggesting, but you could create a new Vue for each element matching your selector.

Each would hold it's own state.

const vues = document.querySelectorAll(".app");
Array.prototype.forEach.call(vues, (el, index) => new Vue({el, data:{message: "hello " + index}}))

Example.

If you wanted a shared state,

const vues = document.querySelectorAll(".app");
const each = Array.prototype.forEach;
const data = {
  message: "hello world"
};
each.call(vues, (el, index) => new Vue({el, data}))

At which point you could do something like data.message = "new value" and all the Vues would change.

Example 2.

This is just me playing around though. It might be advisable for you to just create one Vue and manage all your foos.

Sign up to request clarification or add additional context in comments.

Comments

1

Additionally, if you want to access the html from your js/ts files, you can use vue's ref system.

example:

<template> 
<div ref="example">example</div>
</template>

example.js:

var myExampleDiv = this.$refs.example;

or if your using typescript

example.ts:

const myExampleDiv = this.$refs.example as HTMLElement;

For more information on this: https://v2.vuejs.org/v2/api/#vm-refs

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.