【问题标题】:Why does Vue 3's `setup(props) { props.id }` return undefined为什么 Vue 3 的 `setup(props) { props.id }` 返回 undefined
【发布时间】:2021-07-31 19:36:19
【问题描述】:

为什么setup(props) { props.id }watchEffect(() => fetch(getUrl()) 回调返回undefined,(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, ... }

见下面的代码sn-p;

<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>

【问题讨论】:

    标签: javascript vuejs3 vue-composition-api vue-props


    【解决方案1】:

    使用组合 API (setup(props)),您仍然需要定义组件的 props 是什么。

    这可能看起来像。

    const Post = {
      template: `...`,
      props: {
        id: {
          type: Number,
          required: true
        }
      },
      setup(props) {
        console.log("setup props.id: ", props.id) // now works?
        // etc...
      }
    }
    

    【讨论】:

    • 感谢@Daniel 的回答。只需添加“为什么”部分,文档就说明了; " 执行 setup 时,组件实例尚未创建。因此,您将只能访问以下属性:props(可能仅限 Proxy)、attrs、slots、emit。换句话说,您不会可以访问以下组件选项:数据、计算和方法、“
    猜你喜欢
    • 2021-12-22
    • 1970-01-01
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多