【问题标题】:How to access "Id" in vue.js script如何在 vue.js 脚本中访问“Id”
【发布时间】:2021-05-12 08:56:28
【问题描述】:

我正在尝试使用“this.$refs.cm_count.innerText”在 vue.js 脚本中访问此 id="cm_count",但我无法获得所需的输出。所以我正在努力解决这个问题。如果我做错了,请告诉我如何在 vue.js 脚本中访问这个“Id”和 css
html

<span id="cm_count" ref="cm_count">
    ({{ c_count }})
</span>

这是在 vue.js 中访问 id "cm_count" 并且还需要 vue.js 脚本中的 .css 的正确方法吗
vue.js

this.$refs.cm_count.innerText ='('+ count +')';
this.$refs.cm_count.css('color', '#DB0038');

【问题讨论】:

  • 你的问题的标题不反映你写的内容。
  • 你在做 Vue 倒退。您应该使用{{ }} 插值等将值放入模板中,这将在组件的数据更改时自动反映。像使用 jQuery 一样从组件中操作 DOM 是个坏主意。

标签: html vue.js


【解决方案1】:

在 JS 中,我们选择项目并对其进行操作。在 Vue 中,我们说项目应该如何应对一些变化并让一切运行。在极少数情况下,可能需要选择一个对象并更改其状态,但在您的情况下,您应该使用计算属性:

<span id="cm_count" ref="cm_count" :syle="spanStyles">
    ({{ c_count }})
</span>


computed: {
  spanStyles() {
    return `color:${this.c_count > 5 ? 'red' : 'black'}`;
  }
}

评论后更新

按钮没有 href 属性。这就是为什么我假设你有一个链接。

<a href="linkTo" @click="doSomething">...</a>


data() {
  return {
    isButtonClicked: false
  }
},
methods: {
  doSomething() {
    // you don't need to set a timeout here,
    // but if it goes to the wrong link,
    // you can use it to delay the changing of the link.
    setTimeout(() => this.isButtonClicked = !this.isButtonClicked, 10
  }
},
computed: {
  linkTo() {
    return this.isButtonClicked ? 'link1.com' : link2.com;
  }
}

【讨论】:

  • 谢谢比伦特。解决方案帮助了我。还有一个问题,我必须使用这个“this.$refs.liked_cm.attr('href', '/post_comment_like_remove/' + catid);”。当我们点击按钮时,我想用这个 href 更改该链接
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-07
  • 2021-04-15
  • 2014-07-07
  • 1970-01-01
相关资源
最近更新 更多