在带有参数的函数内部动态使用 Vue $refs

aCa*_*lla 3 javascript parameters function ref vue.js

我正在尝试使用 Vue 访问 DOM 元素,使用该$refs功能,但无法使其正常工作。

我的元素如下所示。PlateId 是动态生成的,因此它不会总是相同的数字:

<textarea :ref="plateId + '-notes'">
Run Code Online (Sandbox Code Playgroud)

我的 Vue 函数如下所示:

/* This does not work */
addNotes: function(plateId) {
    console.log(this.$refs.plateId + '-notes');
}
Run Code Online (Sandbox Code Playgroud)

每当我运行此代码并激活该功能时,它只会undefined在我的控制台中读取。我也试过这个,它也不起作用并且读取未定义:

/* This does not work */
addNotes: function(plateId) {
    var plateIdNotes = plateId + '-notes';
    console.log(this.$refs.plateIdNotes);
}
Run Code Online (Sandbox Code Playgroud)

替换varconst(我正在使用 ES6 并转换代码)也不起作用:

/* This does not work */
addNotes: function(plateId) {
    const plateIdNotes = plateId + '-notes';
    console.log(this.$refs.plateIdNotes);
}
Run Code Online (Sandbox Code Playgroud)

我知道ref正在正确绑定到元素,因为当我在下面执行此操作时,我可以在控制台中看到所有其他引用以及plateId-notes 引用:

/* This works */
addNotes: function(plateId) {
    console.log(this.$refs);
}
Run Code Online (Sandbox Code Playgroud)

如何plateId使用函数中的参数访问ref?

Ham*_*bot 7

你可以使用[]符号:

  methods: {
    foo (id) {
        alert(this.$refs[id + '-test'].innerText)
    }
  }
Run Code Online (Sandbox Code Playgroud)

一个完整的工作示例:https : //jsfiddle.net/drufjsv3/2/

  • 除此之外,如果您在使用“v-for”和动态“refs”制作的一堆组件中使用它,则需要使用“this.$refs[id + '-test'][0].innerText ` 访问该组件中的任何内容 https://vuejs.org/v2/api/#ref (3认同)