在Vue中,不推荐使用this.$refs来获取元素,而是通过ref属性来获取。另外,在Vue中设置自定义属性一般是通过v-bind指令来实现。

你可以在模板中给元素设置自定义属性,如下所示:

<template>
  <div>
    <button ref="myButton" v-bind:data-custom-attr="customValue">Click me</button>
  </div>
</template>

在Vue实例中,你可以在data选项中定义customValue的值,并在mounted生命周期钩子中获取this.$refs.myButton并设置自定义属性,如下所示:

export default {
  data() {
    return {
      customValue: 'custom attribute value'
    }
  },
  mounted() {
    this.$refs.myButton.setAttribute('data-custom-attr', this.customValue);
  }
}

这样就可以给this.$refs.myButton元素设置自定义属性data-custom-attr并赋予值为customValue

vue 给 thisrefs获取到的元素设置自定义属性

原文地址: http://www.cveoy.top/t/topic/h91v 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录