0

I'm trying to load the data for a site from a database using Vue.js. Everything looks nice...the Vue.js data works ok in the console but on the page appears nothing. I'm pretty sure it's not about how I access it because in the console it works fine. Have you any idea what could have gone wrong? Many Thanks!

console view

html

            <div id="featured">
            {{featured[0].list_featured_text}}
            </div>

javascript

        var topArticle=new Vue({
        el:'#featured',
        data:{featured:null},
        created: function(){
                    $.get("featured.php",function(data){
                      this.featured=JSON.parse(data);
                      console.log(this.featured);
                                                        }
                          );
                        }
        });

php

<?php
$servername="localhost";
$username="root";
$passwort="";
$port=3306;
$databname="futurezone";
$conn= new mysqli($servername,$username,$passwort,$databname,$port);
if($conn->connect_error)
die("Connection failed. ". $conn->conn->error);
$conn->query("SET NAMES utf8");

$sql="SELECT * FROM featured";
$result=mysqli_query($conn,$sql) or die("Connection failed.")

$myarray=array();
while($row=mysqli_fetch_assoc($result))
{
$myarray[]=$row;
}
echo json_encode($myarray);
$conn->close();
?>

1 Answer 1

1
$.get("featured.php", function(data) {
    this.featured = JSON.parse(data);
    console.log(this.featured);
});

this inside the callback function is not the same as this outside this function.
To preserve this - use fat-arrow function () => {} or use an inremediate variable like self, for example:

$.get("featured.php", (data) => {
    this.featured = JSON.parse(data);
    console.log(this.featured);
});

or

let self = this;
$.get("featured.php", function(data) {
    self.featured = JSON.parse(data);
    console.log(self.featured);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.