'How to retrieve data from database using Vue

Solved Somehow, as commented by a user, moving the template from the webpage into the vue script solved the problem. I am not completely sure why though. Here is a working fiddle that also works on my setup.

Original Question I have some Laravel experience but am quite new to using Vue. I would like to have a page that displays certain values from a database, when a value is added or deleted, I would like to have the page automatically updated without reloading. I believe this is exactly what you use Vue for.

I'm running Laravel 5.7.16 and installed vue 2.5.21 and vue-resource 1.5.1 using npm install. The database is running on MariaDB 10.1.35.

So far I'm trying to make an http GET request from vue, the GET url has a web route set up, for this route I will make a function that retrieves the data from the database. However, I can't seem to get the http request to work propperly.

These are my files:

webpage.blade.php

@extends('layouts.app')

@section('content')
    <div id="app" class="container">
        <p>@{{ test }}</p>
    </div>

    <script src="{{ asset('js/vue.min.js') }}"></script>
    <script src="{{ asset('js/vue-resource.min.js') }}"></script>
    <script src="{{ asset('js/script.js') }}"></script>
@endsection

Some sources I have found online use the script tag to load in vue, other use 'require' from within a .js file. For me this is working now but I am not sure if this is the best way.

script.js

var vue = new Vue({
el: '#app',

data: {
    test: 'old data',
},

mounted: function() {

    var url = "/test";

    this.$http.get(url).then(response => {

        // get body data
        this.test= response.body;
        return this.test;

    });

}
});

routes/web.php

Route::get('/test', function()
{
    return 'new data';
});

The code above seems to always display 'old data' where I would expect it to display 'new data'. I read somewhere in the vue docs that 'ready' is depricated in Vue 2.x and that I sould use 'mounted' instead. However, it doesn't seem like this function is run while loading the page.

Can someone give a clear example of Vue making an http GET request to retrieve some value and having that value displayed on a web page? I will worry about having it auto updated once I can get this working.



Solution 1:[1]

After you make the HTTP request, you need to set the value of test to the response. For example:

var vue = new Vue({
    el: '#app',

    data: {
        test: 'old data',
    },

    mounted: function() {

        var url = "/test";

        this.$http.get(url).then(response => {
            this.test = response.body; 
        });

    }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1