Vue instance using classes
I am new to Vue and have a few questions. But I think the problem I am working with is such that I have no idea how to solve it:
I have several <div class="foo">
in my code. I want to interact with these <div>
using a Vue instance. I got the idea to use something like:
var app = new Vue({
el: 'div.foo',
data: {
message: 'bar'
}
})
Hence, all elements div.foo
can be controlled with app
. But how can I get EXACTLY the item I'm working with?
Let's say in JQuery we have this ...
$("div.foo").click(function() {
console.log($(this));
})
The code will work for everyone div.foo
, but printing will only show the clicked item.
source to share
You cannot do what you suggest, but you can create a new Vue for every element that matches your selector.
Each of them will contain its own state.
const vues = document.querySelectorAll(".app");
Array.prototype.forEach.call(vues, (el, index) => new Vue({el, data:{message: "hello " + index}}))
If you need general condition,
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 this point, you can do something like data.message = "new value"
and all Vues will change.
It's just me playing around. You might just be able to create one Vue and manage all of your foo
s.
source to share
Also, if you want to access html from js / ts files, you can use vue ref system.
Example:
<template>
<div ref="example">example</div>
</template>
example.js:
var myExampleDiv = this.$refs.example;
or if you are using typescript
example.ts:
const myExampleDiv = this.$refs.example as HTMLElement;
For more information on this: https://vuejs.org/v2/api/#vm-refs
source to share