【问题标题】:How to assign template ref to nested object property如何将模板引用分配给嵌套对象属性
【发布时间】:2023-11-21 07:21:02
【问题描述】:

我的脚本标签如下所示:

<template>
<div>
  <div ref="publicKey.element">Public</div>
  <div ref="privateKey.element">Private</div>
</div>
</template>
<script setup>
const publicKey = {
  element: ref(null),
  onClick: () => alert('public clicked'),
}
const privateKey = {
  element: ref(null),
  onClick: () => alert('private clicked'),
}
</script>

基本上,我不想将模板 ref 分配给*组合 api ref,而是将其应用于嵌套在对象中的 ref。

问题是上面的 ref="publicKey.element" 没有做任何事情 - 当我检查 "element" 属性下的值时,只有常规的 ref 对象并且 _value 为空。

如何在其中放置实际元素?

【问题讨论】:

    标签: vuejs3 vue-composition-api


    【解决方案1】:

    Use the function syntax of the ref="" attribute 文档显示了一个带有 v-for 的示例,但您也可以在没有 v-for 的情况下使用它

    <div>
      <div :ref="el => publicKey.element.value = el">Public</div>
      <div :ref="el => privateKey.element.value = el">Private</div>
    </div>
    

    【讨论】:

      最近更新 更多