vue.js - 如何动态更改 Vue $ref 对象中的类属性?
问题描述
我得到了一个 vue 对象的实例,我在代码中添加了一个类:
this.$refs.myrefs[0].$el.classList.add('className');
但我也想在代码中更改“className”中的某些内容:
.className {
position: absolute;
top: 100px;
left: 100px;
}
我怎样才能做到这一点?我想根据屏幕上的鼠标移动位置更改“顶部”和“左侧”。任何想法?如何访问同一个类并更改其属性值?className 是正在改变的东西。
解决方案
为此,实际上您只需要绑定样式检查文档
<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
推荐阅读
- java - 在后台将 FCM 通知保存在 Room DB 中
- java - 根据位置命名数据库的最佳方式
- python - 如何将python循环代码重写为更简单的代码?
- swift - TypeError:“InputLayer”对象不可与 CoreMLTools 迭代
- c++ - WinUSB 崩溃并出现错误 1450“系统资源不足,无法完成请求的服务”
- python - 从状态文件跟踪 LFTP 下载
- python - 如何从链接中没有文件名的下载 URL 获取文件名
- python - 用python用连续分布的卷积拟合数据
- c# - (ObjectDisposedException) 无法将 FormFile 上传到磁盘空间
- javascript - 在 pm2 中更改进程的端口