如何动态更改 Vue $ref 对象中的 class 属性?

How to change dynamically class attribute in Vue $ref object?

我得到了一个 vue 对象的实例,我在代码中添加了一个 class:

this.$refs.myrefs[0].$el.classList.add('className');

但我也想在代码中更改一些内容 'className':

.className {  
   position: absolute;
   top: 100px;
   left: 100px;
}

我该怎么做?我想更改 'top' 和 'left' ,它们根据鼠标在屏幕上的移动位置而变化。任何的想法?我如何访问相同的 class 并更改其属性值? class名称正在更改。

实际上你只需要绑定样式 检查 doc

<div v-bind:style="styleObject"></div>

data: {
  styleObject: {
    left: 0,
    top: 0
  }
}

然后通过鼠标移动,您只需获取鼠标位置并更新该对象 举个例子

this.styleObject.left = mouseLeft
this.styleObject.top = mouseTop

如果您有许多用于不同 DOM 元素的样式,那么我建议 使用纯 JS

document.getElementById("elementId").style.top = mouseTop
document.getElementById("elementId").style.left = mouseLeft

document.querySelector(".className").style.top = mouseTop
document.querySelector(".className").style.left = mouseLeft