gpt4 book ai didi

javascript - 使用类的 Vue 实例

转载 作者:数据小太阳 更新时间:2023-10-29 04:56:53 26 4
gpt4 key购买 nike

我是 Vue 的新手,有几个问题。但我认为我遇到的问题是我不知道如何解决的问题:

我有几个<div class="foo">在我的代码中。我想与这些互动 <div>使用 Vue 实例。我想到了使用类似的东西:

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

因此,所有 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}}))

Example .

如果你想要共享状态,

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

此时您可以执行类似data.message = "new value" 的操作,所有 Vue 都会发生变化。

Example 2 .

不过这只是我的玩笑。建议您只创建一个 Vue 并管理所有的 foo

关于javascript - 使用类的 Vue 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42962443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com