【问题标题】:Passing data from Node.js to Vue.js将数据从 Node.js 传递到 Vue.js
【发布时间】:2020-05-31 01:24:20
【问题描述】:

我在将数据从 Node.js 代码传递到 Vue.js 时遇到问题

我的 Vue.js 部分:

<p class="align-self-center m-0">Name</p>
<div v-for="info in infos" v-bind:key="info">
   {{info}}
</div>

和 Node.js 部分:

import axios from 'axios';

export default {
  name: 'section1',
  data () {
    return {
      infos:""
    }
  },
  mounted(){    
  let headers = {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
    };
    axios.get('http://localhost:5000/api/v1/profile/5e21990d8d18cf33f8adf94a',{ headers })
    .then( response => {
        var user = JSON.parse( response.data ).results[0]
        console.log(user)
        this.infos = user.name
        })

  }

}

我想将信息(即 user.name)传递给我的视图。 感谢您的帮助。

【问题讨论】:

  • 有什么问题以及预期的行为是什么?
  • 在您的数据中,您有一个名为infos 的值,但在您的模板中,您将其称为info。这不是你的问题吗?

标签: node.js vue.js parameter-passing


【解决方案1】:

提示:

  • 你不需要 axios 或 smth。第三方请求客户端,fetch 工作 everywhere。

  • 可能您的后端会根据您的需要进行响应,只需传入 vue 即可,无需选择需要的内容。

我没有测试下面的代码,但你的问题可能是这样的,如果它解决了你的问题或澄清了什么,请验证答案。

<template>
  <span>Name {{user.name}}</span>
</template>

<script>
export default {
  data() {
    return {
      user: {}
    };
  },
  async mounted() {
    // API URL must be constant, should be in config.
    const API_URL = "http://localhost:5000/api/v1/profile/5e21990d8d18cf33f8adf94a";
    // Custom headers, but no need for content-type.
    const headers = new Headers({
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*"
    });

    // If the fetch fails,
    try {
      // Fetch with custom headers.
      const user = await fetch(API_URL, { headers })
        .then(response => response.json())
        .then(users => users[0]);
      // Then set the user object to data
      this.user = user;
    } catch (err) {
      console.error(err);
    }
  }
};
</script>

【讨论】:

    猜你喜欢
    • 2017-09-15
    • 1970-01-01
    • 2019-01-20
    • 2018-01-13
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 2017-01-25
    • 2017-06-10
    相关资源
    最近更新 更多