如何在Nuxt 3中使用模板引用?

9
在Nuxt2中,您可以通过this.$refs访问<script>中的template $refs
我想知道Nuxt3的等效方法是什么。
我需要这样才能访问元素的innerText。我不允许使用querySelectorgetElementById等。
这是我们编写代码的方式。我可以给html元素ref="fooBar",但我无法使用this.$refs.fooBar甚至this.$refs来访问它。
<script setup lang="ts">
import { ref, computed } from 'vue';

const foo = ref('bar');

function fooBar() {
  //Do stuff
}
</script>

<template>
  //Html here
</template>

在这个例子中,const foo = ref('bar'); 代替了 data() {return {foo:'bar'}} - Marnix Elling
1个回答

10

使用Options API

<script>
export default {
  mounted() {
    console.log('input', this.$refs['my-cool-div'])
  }
}
</script>

<template>
  <div ref="my-cool-div">
    hello there
  </div>
</template>

使用组合式 API
<script setup>
const myCoolDiv = ref(null)

const clickMe = () => console.log(myCoolDiv)
</script>

<template>
  <button @click="clickMe">show me the ref</button>
  <div ref="myCoolDiv">
    hello there
  </div>
</template>

这完全不是我的代码看起来的样子了,我以为这是因为 Nuxt3,但也许是因为我们使用 TypeScript?我们不再使用任何生命周期钩子,我已经更新了问题并附上了我的代码。 - Marnix Elling
1
啊,是的,这个方法可行,感谢你第八次拯救我的生命。所以使用refs的方式不仅适用于nuxt3,还适用于typescript吗?我对两者都很新。 - Marnix Elling
1
@MarnixElling 这实际上是Vue3(Composition API)的事情:https://vuejs.org/api/composition-api-lifecycle.html#onmounted 如果你想正确地输入它,这里有:https://vuejs.org/guide/typescript/composition-api.html#typing-component-template-refs - kissu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接