我尝试使用Vue.js从数据库加载网站的数据。一切看起来都不错...... Vue.js数据在控制台中运行正常但在页面上看不到任何内容。我很确定它不是关于我如何访问它,因为在控制台中它工作正常。你知道出了什么问题吗? 非常感谢!
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();
?>
答案 0 :(得分:1)
$.get("featured.php", function(data) {
this.featured = JSON.parse(data);
console.log(this.featured);
});
回调函数中的 this
与此函数外的this
不同
要保留this
- 请使用胖箭头函数() => {}
或使用像self
这样的内部变量,例如:
$.get("featured.php", (data) => {
this.featured = JSON.parse(data);
console.log(this.featured);
});
或
let self = this;
$.get("featured.php", function(data) {
self.featured = JSON.parse(data);
console.log(self.featured);
});