使用类的Vue实例 [英] Vue instance using classes

查看:74
本文介绍了使用类的Vue实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Vue的新手并且有一些问题。但我认为我正在运行的问题是我不知道如何解决它:

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:

我有一些< div class =我的代码中的foo> 。我想使用Vue实例与这些< div> 进行交互。我有想法使用类似的东西:

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'
  }
})

因此,所有 div.foo 元素都可以通过 app 进行管理。但是我怎样才能得到我正在使用的元素呢?

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

让我们说在JQuery中我们有这个......

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

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

该代码适用于每个 div.foo ,但是打印将只显示点击的元素。

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

推荐答案

你不能按照你的意思做,但是你可以创建一个与您的选择器匹配的每个元素的新Vue。

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}}))

示例

如果您想要共享状态,

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的操作,并且所有Vues都会更改。

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

示例2

这只是我在玩。您可能建议只创建一个Vue并管理所有 foo s。

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

这篇关于使用类的Vue实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆