如何在 vue.js 中添加动态引用?

新手上路,请多包涵

我的 dom 中有一些动态的 <input> 元素是从 vue 中的 for 循环渲染的。我需要通过将 Id 附加到每个 ref (如 element1、element2 等)来为它们中的每一个添加 ref 属性。如何在 vue 中做到这一点?

 <div v-for="(result, index) in data" :key="index">
    <input type="text" type="file" ref="element" />
</div>

如何添加 ref 如果 result.id 存在

原文由 LJP 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 317
2 个回答

只需使用 v-bind:ref="'element' + result.id"ref="`element${result.id}`"

在这里检查小提琴

 new Vue({
  el: '#app',
  data: {
    data: [{id: 1}, {id: 2}, {id: 3}],
  },
  mounted() {
    console.log(this.$refs);
  }
})
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>

<div id="app">
<div v-for="(result, index) in data" :key="index">
    <input type="text" type="file" :ref="'element' + result.id" />
</div>
</div>

编辑:感谢 Vamsi 的编辑,我将 index 替换为 result.id

828 编辑:感谢 grokpot,我添加了一个由模板文字提供支持的示例。

原文由 choasia 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 v-bind:ref 或只是 :ref

下面是一个简单的例子,包括如何访问动态 ref

 <template>
    <div>
        <div class="inputs" v-for="input in inputs" :key="input.id">
            <input type="text" v-model="input.name" :ref="'name' + input.id">
            <button @click="displayRef('name' + input.id)">
                 Click to see the input ref
            </button>
            <hr>
            <button @click="displayAllRefs">Click to see all refs</button>
        </div>
    </div>
</template>

和脚本:

 <script>
    export default {
        data() {
            return {
                inputs: [
                    { id: Date.now(), name: '', lastName: '' }
                ]
            }
        },
        methods: {
            displayRef(ref) {
                console.log(this.$refs[ref]) // <= accessing the dynamic ref
                console.log('The value of input is:',this.$refs[ref][0].value) //<= outpouting value of input
            },
            displayAllRefs() {
                console.log(this.$refs)
            }
        }
    }
</script>

原文由 Roland 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏