vue.js - Vue 3 模板引用动态名称

标签 vue.js vuejs3 vue-composition-api vue-script-setup

我注意到要在 Vue 3 组合 api 中制作模板引用 <script setup> ,我应该创建一个与 ref 值完全相同的变量名。

例如 Vue 3 documentation :

<template>
  <div ref="root">This is a root element</div>   <--- notice the ref name "root"
</template>

<script>
  import { ref, onMounted } from 'vue'

  export default {
    setup() {
      const root = ref(null)   <---- and the variable name should be "root" too

      onMounted(() => {
        console.log(root.value) 
      })

      return {
        root
      }
    }
  }
</script>

我想知道我是否可以像 Vue 2 那样使用 ref,因为我有一些元素,其 ref 是随机字符串,它在 Vue 2 上工作,只需在 $refs 上传递名称即可对象。

<div ref="myCustomRefName"></div>

<script>
let myRef = this.$refs["myCustomRefName"]
</script>

但我不能那样做,因为在 Vue3 中,我应该使变量名和 ref prop 值相似。任何帮助将不胜感激。

最佳答案

对我有用的是以下内容

<template>
  <div ref="root">This is a root element</div>   <--- notice the ref name "root"
  <div ref="foo">this is foo element</div>
  <div ref="bar">this is bar element</div>
</template>

<script>
  import { ref, onMounted } from 'vue'

  export default {
    setup() {
      const refs = {
         root = ref(null), //<---- and the variable name should be "root" too
         foo = ref(null),
         bar = ref(null)
      }
      onMounted(() => {
        console.log(root.value)
        console.log(refs["root"])
      })

      return {
        ...refs
      }
    }
  }
</script>

只需创建一个对象 refs(我将其称为 refs 只是因为怀旧)并使用您拥有的任何动态名称进行调用。

关于vue.js - Vue 3 模板引用动态名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68789245/

相关文章:

vue.js - 未定义 vue 3 脚本设置 onBeforeMount

vue.js - Vue3 : How to override function with the composition API?

excel - 注册 onSelectionChange

javascript - 使用 VueJs 获取选择选项文本

vue.js - 无法在 vue 3 组合 api 中的组件上使用模板引用

javascript - 在Vue js中设置<select>选项的默认动态值

vue.js - 如何比通过 const 更明确地声明变量?

Vue.js 3 在方法中使用 ref 对输入使用自动对焦

javascript - 修改数据表中的特定td

vue.js - Vue 计算不起作用