Vue.js component is failing to display on the page

I am struggling with a component that should use axios to fetch some data for my page, but the request is not being made. Below is the code snippet:

Snippet from App.vue:

<template>
  <div id="app">
    <Prices/>
  </div>
</template>

<script>
import Prices from './components/Prices.vue'

export default {
  name: 'app',
  components: {
    Prices
  }
}
</script>

Snippet from Prices.vue:

<template>
  <div>
    <p>{{ info }}</p>
  </div>
</template>

<script>
export default {
  name: 'Prices',
  props: {
    info: String
  }
}
</script>

Snippet from main.js:

import Vue from 'vue/dist/vue.js';
import App from './App.vue'
import './registerServiceWorker'
import axios from 'axios'

Vue.config.productionTip = false

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

This is my first app using Vue.js and I am unsure of what is causing the issue. Any guidance on how to resolve this problem would be greatly appreciated.

Answer №1

Ensure to set the data property from the response to your info property in this way:

 .then(response => (this.info = response.data))

Then, pass the info property through props to the child component like this:

  <Prices :info='info'/>

Update the content in app.vue as shown below:

<template>
  <div id="app">
    <Prices :info='info'/>
  </div>
</template>

<script>
import Prices from './components/Prices.vue'

export default {
  name: 'app',
    data () {
    return {
      info: null
    }
  },
  components: {
    Prices
  },
  mounted () {
    this.axios  //<--- use this.axios instead of `axios`
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => (this.info = response.data))
  }
}
</script>

Make changes to main.js :

import Vue from 'vue/dist/vue.js';
import App from './App.vue'
import './registerServiceWorker'
import axios from 'axios';
import vueAxios from 'vue-axios';
Vue.use(vueAxios,axios); //add Vue.use(axios)
Vue.config.productionTip = false new Vue({
  render: h => h(App),
  data() {
    return {}
  }
}).$mount('#app')

Please Note

Don't forget to install vue-axios using the command below:

   npm install --save vue-axios

Lastly, make sure to use it along with axios like this:

    import axios from 'axios';
    import vueAxios from 'vue-axios';
    Vue.use(vueAxios,axios); //add Vue.use(axios)

Answer №2

To successfully run the application, make sure you pass in the necessary props.

Instead of fetching data in the main.js file, move the task to the app component.

<template>
  <div id="app">
    <Prices :info="info"/>
  </div>
</template>

<script>
import Prices from './components/Prices.vue'

export default {
  name: 'app',
  data () {
    return {
      info: null
    }
  },
  components: {
    Prices
  },
  mounted () {
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => (this.info = response.data))
  }
}
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leverage JavaScript to showcase Django object on the webpage

I am trying to achieve the following using javascript: when a row is clicked, it should retrieve the index and display the object at that index. This functionality works in a django template. <div>{{ project.0.customer_name}}</div> <div> ...

Modifying the $scope within a controller

I need to update the $scope within the controller based on the object that is being clicked. The current code looks like this: var blogApp = angular.module('blogApp', ['ngSanitize', 'ngRoute']); blogApp.controller('blog ...

Error: Material-UI prop type validation failed - Please specify either `children`, `image`, `src`, or `component` prop

Despite having an image prop in CardMedia, I kept encountering this error. Here is a snippet of the code: Error description: const Post = ({ post, setter }) => { const classes = useStyles(); return( <Card className={classes.card} ...

Combining objects using mathematical operations for identical properties in JavaScript

Imagine I have two sets of data: const obj1 = { CRITICAL: 0, ERROR: 1, INFO: 0, WARNING: 0, }; const obj2 = { CRITICAL: 0, ERROR: 0, INFO: 0, WARNING: 1, }; I'm looking to merge them into a single object with the summed values for e ...

Re-enable VueJS Devtools during the development process

While working in my homestead development environment, I decided to run the command npm run production to test if the vuejs devtools would disappear and make sure everything was functioning properly. Surprisingly, the devtools did vanish. Now, I am struggl ...

Switching videos dynamically with JavaScript while utilizing Bootstrap to enable playback in a floating window

This is a piece of code that enables playing videos in floating windows using Bootstrap. However, I am looking to enhance the functionality by dynamically changing the video source using JavaScript. I tried using onClick() to modify the src attribute of th ...

What to do when the 'image' property in Next.js next/image has an implicit 'any' type and needs fixing?

I'm a newcomer to Next.js and TypeScript and I can't seem to find any helpful resources on resolving this particular issue: import Image from 'next/image'; export default function Item({ image }) { // <-- parameter image needs a &ap ...

Tips for customizing bootstrap's fixed navbar-default to ensure that the list items align downwards:

Is it possible to customize the bootstrap fixed navbar-default so that the li elements align downward instead of at the top? If you have any corrections or custom solutions, I'd love to see them! Feel free to share your code on platforms like CodePen, ...

How to adjust the timezone settings in PHPMyAdmin on a shared server platform

I'm having trouble changing my timezone to India on my shared server database. I've tried everything but can't seem to get it to work. My website is built using PHP Codeigniter The contact us page on my site saves all inquiry details to my ...

Transforming Observable into a Promise

Is it considered a best practice to convert an observable object to a promise, given that observables can be used in most scenarios instead of promises? I recently started learning Angular and came across the following code snippet in a new project using ...

Encountering an issue while invoking the helper function in Vuejs

Main view: <script> import { testMethod1 } from "../helper"; export default { methods: { init(){ console.log("Res:", testMethod1()); } } } </script> Helper: import DataService from "../services/data. ...

Removing the element generated by Angular from the DOM

I've hit a roadblock with this issue. Here is the delete function in my mainController. $scope.delete = function($posts) { $http.delete('/api/posts/' + $posts._id) .success(function(data) { // remove element from DOM ...

What is the best way to access a specific value within a two-layered JSON object using JavaScript?

Here is an example of JSON data that I am working with: {"0":{"access_token":"ya29.MgCIagT8PCpkRSIAAAAl-XYEA37OjX_GBAv4so6qv0Gowc5XD3Bp6MuwYAPmnNuwgz7ElXsRwXqGWL4aZpA","token_type":"Bearer","expires_in":"3600","scope":"https://www.googleapis.com/auth/plus ...

Axios failing to include Content-Type in header

I have set up an Odoo instance in the backend and developed a custom module that includes a web controller. Here is the code for the web controller: Web Controller # -*- coding: utf-8 -*- from odoo import http import odoo from odoo.http import Response, ...

Guide on adding pictures to an ExpressJS server

Working on this project has been quite a challenge for me as I delve deeper into web development. As a relatively new developer, creating a one-page application with image upload functionality has proven to be quite the task, especially considering this is ...

Customize Button Colors in Bootstrap 4

I'm encountering difficulties when attempting to change the color of the buttons labeled "Print," "Excel," and "PDF". Despite referring to a guide, I wasn't able to succeed. The provided test case differs from my code but shares the same CSS and ...

What is the best way to add a color swatch image using Javascript?

I'm facing a challenge in Shopify where I need to assign corresponding background images to color swatches. Currently, my icons are set up with the correct links for each color, but they are missing their respective images, similar to this example. I ...

Include a fresh attribute in the Interface

How can I include a boolean property isPhotoSelected: boolean = false; in an API interface that I cannot modify? The current interface looks like this: export interface LibraryItem { id: string; photoURL: string; thumbnailURL: string; fi ...

Steps to deactivate a ladda button

I'm currently utilizing Ladda UI for bootstrap in my project. My goal is to disable a button using jQuery after the user clicks on it. Despite attempting to use ajax OnComplete / OnSuccess / OnBegin, I've had no luck - the button remains enable ...

Having trouble fetching configuration values with Vue.js

console.log(process.env.test); displays "undefined" in the console. In the dev.env.js file, I have the following configuration. Do you see anything that I might have overlooked? 'use strict' const merge = require('webpack-merge') con ...