【问题标题】:Dynamic axios request url in Vue 3 ComposablesVue 3 Composables 中的动态 axios 请求 url
【发布时间】:2022-11-10 23:02:07
【问题描述】:

我已经尝试过了,它奏效了:

    const posts = ref{[]}
    const urlEndPoint = 'posts'

    const getPosts = async () => {
           let response = await axios.get('/api/'+urlEndPoint)
              posts.value = response.data.data
          }

但那不是动态的。我的目标是使 urlEndPoint 值具有反应性并从组件中设置

然后我尝试了这个:

const urlEndPoint = ref([])

但我不知道如何将urlEndPoint 常量的值从component 发送回composables

我在我的组件中尝试了这些:

const urlEndPoint = 'posts'

const sendUrlEndPoint = () => {
        urlEndPoint = 'posts'
    }

但没有一个工作。

有没有办法实现这个目标?就像以可组合或任何其他简单方式将组件名称发送到 urlEndPoint 值。

【问题讨论】:

    标签: laravel vuejs3 vue-composition-api vue-script-setup composable


    【解决方案1】:

    定义一个名为 use useFetch 的可组合函数:

    import {ref} from 'vue'
    export default useFetch(){
    
       const data=ref([])
    
       const getData = async (urlEndPoint) => {
               let response = await axios.get('/api/'+urlEndPoint)
                  data.value = response.data.data
              }
    
      return {
         getData,data
     }
    
    

    在您的组件中导入该函数并像这样使用它:

    const urlEndPoint=ref('posts')
    const {getData:getPosts, data:posts}=useFetch()
    
    getPosts(urlEndPoint.value)
    
    
    
    

    【讨论】:

    • 这个第一次尝试就实现了我的目标。
    • 答案令人困惑,因为它确实创建了一个 ref urlEndPoint 但随后不使用它。另外,您必须在 getData 函数中使用 urlEndPoint.value ,否则它将不起作用。
    • @NicolaiEhemann 你是对的,urlEndPoint 没有被使用,它应该被删除或添加为像 getPosts(urlEndPoint.value) 这样的参数
    猜你喜欢
    • 2019-02-12
    • 2020-10-11
    • 2020-02-14
    • 2019-09-29
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 2019-10-01
    相关资源
    最近更新 更多