Vue 实例使用类 [英] Vue instance using classes
问题描述
我是 Vue 的新手,有一些关于它的问题.但我认为我正在运行的问题是我不知道如何解决它:
我的代码中有一些 <div class="foo">
.我想使用 Vue 实例与这些
var app = new Vue({el: 'div.foo',数据: {消息:'酒吧'}})
因此,所有 div.foo
元素都可以由 app
管理.但是我怎样才能得到我正在使用的元素呢?
假设在 JQuery 中我们有这个...
$("div.foo").click(function() {console.log($(this));})
该代码适用于每个 div.foo
,但打印将只显示被点击的元素.
你不能按照你的建议去做,但你可以为每个匹配你的选择器的元素创建一个新的 Vue.
每个人都拥有自己的状态.
const vues = document.querySelectorAll(".app");Array.prototype.forEach.call(vues, (el, index) => new Vue({el, data:{message: "hello " + index}}))
示例.
如果您想要共享状态,
const vues = document.querySelectorAll(".app");const each = Array.prototype.forEach;常量数据 = {消息:你好世界"};each.call(vues, (el, index) => new Vue({el, data}))
此时你可以做一些类似 data.message = "new value"
的事情,所有的 Vue 都会改变.
示例 2.
这只是我在玩.建议您只创建一个 Vue 并管理您所有的 foo
.
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.
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}}))
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.
This is just me playing around though. It might be advisable for you to just create one Vue and manage all your foo
s.
这篇关于Vue 实例使用类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!