<p>本文将分析并修复一段使用 Vue 3 的 `<script setup>` 语法的代码中的错误,其中涉及 `watch` 函数和数据导出。以下代码示例中存在两个错误: </p>
<pre><code><script setup>
import { ref, watch } from 'vue'

const todoId = ref(1)
const todoData = ref(null)

async function fetchData() {
  todoData.value = null
  const res = await fetch(
    `https://jsonplaceholder.typicode.com/todos/${todoId.value}`
  )
  todoData.value = await res.json()
}

fetchData()
watch(todoId,todoData)
</script>
<template>
  <p>Todo id: {{ todoId }}</p>
  <button @click="todoId++">Fetch next todo</button>
  <p v-if="!todoData">Loading...</p>
  <pre v-else>{{ todoData }}</pre>
</template></code></pre>
<h4>错误 1: `watch` 函数的使用方式不正确</h4>
<p>在你的代码中,`watch(todoId, todoData)` 的使用方式存在错误。`watch` 函数需要两个参数: </p>
<ul>
  <li>第一个参数是要监听的响应式数据。 </li>
  <li>第二个参数是当响应式数据发生变化时要执行的回调函数。 </li>
</ul>
<p>在你的代码中,你传递了 `todoData` 作为第一个参数,但没有提供第二个参数。应该将 `watch(todoId, todoData)` 修改为 `watch(todoId, fetchData)`,这样当 `todoId` 变化时,会自动执行 `fetchData` 函数。 </p>
<h4>错误 2: 模板中无法访问 `todoId`</h4>
<p>在模板中,你使用了 `{{ todoId }}` 来展示当前的 `todoId` 值,但是你在 `setup` 部分没有将 `todoId` 导出给模板使用。你需要在 `setup` 部分返回一个对象,将 `todoId` 添加到该对象中,并在模板中使用该对象的成员来展示 `todoId` 值。 </p>
<h4>解决方案</h4>
<p>以下代码展示了修复后的代码: </p>
<pre><code><script setup>
import { ref, watch } from 'vue'

const todoId = ref(1)
const todoData = ref(null)

async function fetchData() {
  todoData.value = null
  const res = await fetch(
    `https://jsonplaceholder.typicode.com/todos/${todoId.value}`
  )
  todoData.value = await res.json()
}

watch(todoId, fetchData)

// 导出给模板使用的数据
return {
  todoId,
  todoData,
  fetchData
}
</script>
<template>
  <p>Todo id: {{ todoId }}</p>
  <button @click="todoId++">Fetch next todo</button>
  <p v-if="!todoData">Loading...</p>
  <pre v-else>{{ todoData }}</pre>
</template></code></pre>
<p>通过以上修复,代码能够正常运行,并在模板中展示 `todoId` 和 `todoData` 的值。 </p>
<p>需要注意的是,Vue 3 的 `<script setup>` 语法是实验性的,可能在未来版本中有所改变。确保使用的是 Vue 3 的最新版本,并查看 Vue 官方文档以获取最新的 `<script setup>` 用法。 </p>

原文地址: https://www.cveoy.top/t/topic/piSo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录