【问题标题】:How to extract axios response data into variables in vuejs如何将axios响应数据提取到vuejs中的变量中
【发布时间】:2018-08-23 02:15:16
【问题描述】:

我正在尝试实现与 Vue 中的 ...mapState() 函数相同的功能。

我有一个 axios 请求,它返回一个具有不同 props 的对象,如下所示:

axios.get(
 '/'
).then(
 res => {
  console.log(res) // {name: 'foo', age: 22, height: '1.72m', job: 'developer'}
 }
)

现在,我可以像 ...mapState() 一样提取道具,以便在我的模板中使用它们,例如:

<template>
 <div> 
  Hello My name is {{name}} and I am {{age}} years old
 </div>
</template>

我正在考虑将响应对象分配给 vuejs 数据,但我有其他变量我不想重写

【问题讨论】:

    标签: javascript vuejs2


    【解决方案1】:

    你可以试试这个:

    axios.get(
     '/'
    ).then(
     res => {
      console.log(res) // {name: 'foo', age: 22, height: '1.72m', job: 'developer'}
      return { index: res}
     }
    )
    

    然后你就可以访问数据了

    <template>
     <div> 
      Hello My name is {{index.name}} and I am {{index.age}} years old
     </div>
    </template>
    

    【讨论】:

    • 这似乎比我得到的其他(已删除)答案更好。你确定它有效吗?没有任何东西将 {{index}} 绑定到全局变量
    • 我不知道你的意思是什么?使用 {{index.name}} 获取值
    • console.log(res) 的确切结果是什么?
    • 响应正常,只是插值不起作用
    猜你喜欢
    • 2020-03-22
    • 1970-01-01
    • 2020-11-02
    • 2022-01-15
    • 1970-01-01
    • 2021-10-10
    • 2021-07-19
    • 1970-01-01
    • 2019-12-18
    相关资源
    最近更新 更多