为什么 Vue 3 的 `setup(props) { props.id }` return 未定义
Why does Vue 3's `setup(props) { props.id }` return undefined
为什么 setup(props) { props.id }
return undefined
来自 watchEffect(() => fetch(getUrl())
回调,(Vue 3 watchEffect
函数)?
使用函数 useFetch(() => url)
的示例
即
const { data, error, isPending } = useFetch(() => https://jsonplaceholder.typicode.com/todos/${props.id})
结果为 https://jsonplaceholder.typicode.com/todos/undefined
预计:https://jsonplaceholder.typicode.com/todos/1 // id++ { 2, 3, ... }
查看下面的代码片段;
<script src="https://unpkg.com/vue@next"></script>
<div id="app"></div>
<script>
const { createApp, ref, watchEffect } = Vue;
useFetch(getUrl => {
const data = ref(null)
const error = ref(null)
const isPending = ref(true)
watchEffect(() => fetch(getUrl())
isPending.value = true
data.value = null
error.value = null
return { data, error, isPending }
})
const Post = {
template: `...`,
setup(props) {
console.log("setup props.id: ", props.id) // returns undefined
const { data, error, isPending } = useFetch(() => `https://jsonplaceholder.typicode.com/todos/${props.id}`) // jsonplaceholder.typicode.com/todos/undefined
}
}
const App = {
components: { Post },
data() {
return {
id: 1
}
},
template: `
<button @click="id++">change ID</button>
<Post :id="id"/>
`
}
createApp(App).mount("#app");
</script>
使用组合 API (setup(props)
) 您仍然需要定义组件道具是什么。
这可能是这样的。
const Post = {
template: `...`,
props: {
id: {
type: Number,
required: true
}
},
setup(props) {
console.log("setup props.id: ", props.id) // now works
// etc...
}
}
为什么 setup(props) { props.id }
return undefined
来自 watchEffect(() => fetch(getUrl())
回调,(Vue 3 watchEffect
函数)?
使用函数 useFetch(() => url)
即
const { data, error, isPending } = useFetch(() => https://jsonplaceholder.typicode.com/todos/${props.id})
结果为 https://jsonplaceholder.typicode.com/todos/undefined
预计:https://jsonplaceholder.typicode.com/todos/1 // id++ { 2, 3, ... }
查看下面的代码片段;
<script src="https://unpkg.com/vue@next"></script>
<div id="app"></div>
<script>
const { createApp, ref, watchEffect } = Vue;
useFetch(getUrl => {
const data = ref(null)
const error = ref(null)
const isPending = ref(true)
watchEffect(() => fetch(getUrl())
isPending.value = true
data.value = null
error.value = null
return { data, error, isPending }
})
const Post = {
template: `...`,
setup(props) {
console.log("setup props.id: ", props.id) // returns undefined
const { data, error, isPending } = useFetch(() => `https://jsonplaceholder.typicode.com/todos/${props.id}`) // jsonplaceholder.typicode.com/todos/undefined
}
}
const App = {
components: { Post },
data() {
return {
id: 1
}
},
template: `
<button @click="id++">change ID</button>
<Post :id="id"/>
`
}
createApp(App).mount("#app");
</script>
使用组合 API (setup(props)
) 您仍然需要定义组件道具是什么。
这可能是这样的。
const Post = {
template: `...`,
props: {
id: {
type: Number,
required: true
}
},
setup(props) {
console.log("setup props.id: ", props.id) // now works
// etc...
}
}