首页 > 解决方案 > 如何动态更改 Vue $ref 对象中的类属性?

问题描述

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

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

但我也想在代码中更改“className”中的某些内容:

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

我怎样才能做到这一点?我想根据屏幕上的鼠标移动位置更改“顶部”和“左侧”。任何想法?如何访问同一个类并更改其属性值?className 是正在改变的东西。

标签: vue.jsvuejs2

解决方案


为此,实际上您只需要绑定样式检查文档

<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

推荐阅读