Exploring the functionality of the get method in Vue

Can you help me figure out how to properly send a get method from Vue in an HTML file? Here's the code I have:

<html>
    <head>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="myDiv">
            <p>{{something}}</p>
        </div>
    </body>
    <script>
        new Vue({
            el: '#myDiv',
            data: function(){
                return{
                    something: ''
                }
            },
            ready: function(){
                this.getValue();
            },
            methods: {
                getValue: function(){
                    var value = value;
                    this.$http.get('https://jsonplaceholder.typicode.com/posts/1')
                        .success(function(value){
                            this.$set('value',value);
                        })
                        .error(function(err){
                            value.log(err);
                        });
                }
            }
        });
    </script>
</html>

I'm trying to display the response as a string in the div with id="myDiv". Imagine my response is a simple JSON object:

{
   "name":"Jon",
   "age":1
}

Even though there are no errors in the console, my screen remains blank. Any idea why?

@Update: Here's what I see on my screen:

https://i.sstatic.net/34S7c.jpg

@Update2 Refined version of my HTML file (based on your suggestions):

<html>
    <head>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="myDiv">
          <div v-if="response.userId">
            {{ response.userId }}
            {{ response.id }}
            {{ response.title }}
            {{ response.body }}
          </div>
          <div v-if="response.error">
            <p>Request failed</p>
          </div>
    </div>
    </body>
    <script>
        var vm = new Vue({
          el: '#myDiv',
          data: {
                response: {}
          },
          created() {
          this
           .$http
           .get('https://jsonplaceholder.typicode.com/posts/1')
           .then(function(response) {
             console.log(response)
             this.$set('response', response.data)
           })
          }
        });
    </script>
</html>

Answer №1

<html>
    <head>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/vue.resource/1.2.0/vue-resource.min.js"></script>
    </head>
    <body>
        <div id="myDiv">
          <div v-if="response.userId">
            {{ response.userId }}
            {{ response.id }}
            {{ response.title }}
            {{ response.body }}
          </div>
          <div v-if="response.error">
            <p>Request failed</p>
          </div>
    </div>
    </body>
    <script>
        var vm = new Vue({
          el: '#myDiv',
          data: {
            response: {}
          },
          created() {
          this
           .$http
           .get('https://jsonplaceholder.typicode.com/posts/1')
           .then(function(response) {
             console.log(response)
             this.response = response.data
           })
          }
        });
    </script>
</html>

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

"Can we apply a filter to the JSON file when it is

I encountered an issue while trying to filter json data based on user selection. The debugger console displayed the error message: TypeError: obj.contacts.filter is not a function. I have included a snippet of my code below: var contactStorage = {}; $(" ...

Tips for showing form values in pop-up boxes based on their unique identifiers

I am experiencing an issue with displaying posted values in a pop-up box. Specifically, when I click on "Book now", it only shows one set of id values for all entries. For example, if I click on the 1st row's "Book now" button, it displays the values ...

Issues with Regular Expressions in JavaScript

I've been attempting to utilize RegEx for extracting data from a string, but unfortunately, I keep receiving a NULL value as the output. Below is the code snippet in question: var re = /(\[cid=(?:[0-9]*)(?:(?:,\[[^]]*\][^]]*)?|(? ...

Adding an interactive element to a predetermined collection

CSS <button class='btn' data-next="games" data-prev="games1" data-storage="128" data-graphcard="2" data-processor="i3">Click Here</button> JavaScript. let components = ["storage", "graphcard", "processor"]; const allBtnsToStore = d ...

Is there a way to transfer data from a child component to a parent component upon clicking, even if they are

I'm currently developing a map application using react.js. My goal is to send the lat and lng values from the Markers component when it's clicked to the App Component. However, there seems to be an issue as the App.js isn't directly connecte ...

Ensure that the form validation process includes a Captcha code for added

Can you demonstrate how to incorporate the following code into a validation check within a form: $("form").clientSideCaptcha({ input: "#captchaText", display: "#captcha", pass : function() { alert("Verification succe ...

The operation of Ajax can be intermittent, as it may run at

I'm encountering an issue with my ajax code. I am adding data from my database and attempting to refresh a div element. It seems to work sometimes but not consistently. Why is that? Here's the problem - I have a function called addtoqueue. Insid ...

Error: The specified schema for the model "superheroes" is missing and has not been registered. Please ensure the schema is properly defined and registered

After updating my server with nodemon, I encountered the following error: C:\Users\mikae\Desktop\Project\node-express-swig-mongo\node_modules\mongoose\lib\index.js:523 throw new mongoose.Error.MissingSchem ...

Error message: CORS policy prevents third-party scripts from running in Next.js

I am encountering an issue with implementing a script handling tool in my Next.js project. I followed the documentation on nextjs.org and utilized the worker (experimental) parameter to enhance the page's performance. However, I am facing a CORS polic ...

Empty refreshToken in aws-amplify's javascript

Utilizing aws-amplify, my configuration looks like this: Amplify.configure({ Auth: { region: config.aws.region, identityPoolRegion: config.aws.region, userPoolId: process.env.userPoolId, userPoolWebClientId: process.env.appClientI ...

"Utilizing ESLint on Vue Components with Multiple Words in Their

Is there a solution to prevent ESLint errors for single word view names in Vue3? Whenever I run ESLint, I receive the following message: 1:1 error Component name "About" should always be multi-word vue/multi-word-component-names This is my current s ...

Problem with using puppeteer to interact with a dropdown menu

I have a project in which I am utilizing puppeteer to create a bot that can automatically check for my college homework assignments. The problem I am encountering is that when the bot tries to click on a dropdown menu, it fails and I receive an error messa ...

How come I am unable to retrieve the new state value from a different function in my react.js hook?

After setting my marinaList to a new value, I encounter an issue when trying to access the current state of marinaList in the GetCounterConnectionDevices function. Despite being able to access marinaList state in the GetMarinaList function, why am I unab ...

Creating a File Upload Progress Bar with jQuery

I am encountering a strange issue that has me puzzled. The problem arose when I created a file upload form with a progress bar using a script from Malsup jQuery Form. Initially, everything worked perfectly. The progress indicator displayed in a light gre ...

Flipping and rotating images using the power of HTML5 Canvas

Hello, I need assistance with my Electron app that arranges images for batch printing on an industrial printer. The issue I am facing is with images flipping or being mirrored unpredictably. Below is the code snippet responsible for determining whether an ...

Adjust the height of the container to accommodate responsive images automatically

Hello, I am trying to make the container height adjust automatically based on the responsive image it contains. The container's display is set to flex and the image is positioned between two divs with the class "text-block". These divs have a width of ...

How can Angular help optimize an array by implementing specific conditions for reduction?

In my database, I have an ordered array that looks like this: let data = [ {month: 1, visible: true}, {month: 2, visible: false}, {month: 3, visible: true}, {month: 4, visible: false}, {month: 5, visibl ...

Add an item to an array and then transform the array into a JSON format

I have a situation where I am creating an object and pushing it into an array. After that, I convert it into JSON format. When I display the dataCharts using an alert, it is returned in this form: [{"AllLinks":"Link9","LinkURL":"url1"},{"AllLinks":"Link6" ...

A comprehensive guide on implementing router-links in Vue.js

As someone new to laravel-vue, I encountered an issue with router-link while trying to display data from the database. Everything seemed to be working fine until I tried setting the path for the router link, which resulted in it not functioning properly. ...

Utilize a single module import across multiple child processes

While working on implementing sharding for my Discord bot using Discord.js, I encountered an issue. Each shard, when in process mode, runs its own program, effectively making each shard operate as a separate bot. One of the features of my bot requires user ...