【问题标题】:Basic HTTP request in VueJSVueJS 中的基本 HTTP 请求
【发布时间】:2020-10-23 14:17:01
【问题描述】:

我对 Vue 完全陌生,我正在“随时随地”学习一些代码,如果我的问题很愚蠢,我很抱歉。我只是想提出一个请求并显示结果。

使用下面的代码,{{info}} 不显示任何内容,我也没有收到任何错误...我错过了什么?

idk.js:

import Vue from 'vue'
import axios from 'axios'

new Vue({
  el: '#idk',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => (this.info = response))
  }
})

Page2.vue:

<template>
  <div id="idk">
  {{ info }} hmm
  </div>

</template>

App.js

import Vue from 'vue'
import App from './App.vue'

// Vuesax Component Framework
import Vuesax from 'vuesax'
import 'material-icons/iconfont/material-icons.css' //Material Icons
import 'vuesax/dist/vuesax.css' // Vuesax
Vue.use(Vuesax)

import './idk.js'
// Styles: SCSS
import './assets/scss/main.scss'
// Tailwind
import '@/assets/css/main.css'
// Vue Router
import router from './router'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

【问题讨论】:

  • 为什么要创建两个vue实例?
  • 试试this.info = response.data。见github.com/axios/axios#response-schema
  • 那行不通。问题似乎不是来自请求,如果我硬核一个值,它也是空的。似乎我误解了 aboue vue 实例,应该只有 1 个吧?

标签: node.js vue.js frontend vue-component


【解决方案1】:

idk.js 逻辑移动到您的Page2 组件中。问题是当您包含idk.js 时,ID 为idk 的元素将不存在。

例如,假设 Page2 包含在 App 或类似的东西中......

<!-- Page2.vue -->
<template>
  <div id="idk">
  {{ info }} hmm
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data: () => ({ info: null }),
  created () { // ? created runs earlier so will get your data quicker
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => {
        this.info = response.data // ? note "response.data" here
      })
  }
})
</script>

然后您可以删除idk.js

【讨论】:

  • 谢谢,我好像有点误解了 vue ......所以我似乎永远不应该创建另一个 vue 实例,而是使用导出默认值。 + 改掉拆分js、css和模板的坏习惯
猜你喜欢
  • 1970-01-01
  • 2018-05-04
  • 1970-01-01
  • 1970-01-01
  • 2018-08-27
  • 1970-01-01
  • 1970-01-01
  • 2017-07-23
  • 1970-01-01
相关资源
最近更新 更多