Vue.js页面无内容显示求助:控制台数据正常但页面不渲染
问题排查与解决办法
嘿,我帮你找出了几个导致页面没内容的核心问题,咱们一个个来解决:
1. 回调函数里的this指向不对!
你在jQuery的$.get回调里用this.featured赋值,但这里的this根本不是Vue实例,而是回调函数自己的上下文!所以数据根本没存到Vue的data里,控制台能打印数据是因为你拿到了返回值,但Vue实例的featured还是初始的null,页面自然没东西。
修复方法:
要么在回调外面先把Vue实例的this存起来,要么用ES6的箭头函数(箭头函数会继承外层的this):
var topArticle=new Vue({ el:'#featured', data:{ featured: [] // 这里先改成空数组,后面说原因 }, created: function(){ // 方法一:保存Vue实例的引用 const vm = this; $.get("featured.php",function(data){ vm.featured = JSON.parse(data); console.log(vm.featured); }); // 方法二:用箭头函数 // $.get("featured.php", (data) => { // this.featured = JSON.parse(data); // console.log(this.featured); // }); } });
2. 初始值为null导致模板渲染报错
你模板里直接写{{featured[0].list_featured_text}},但一开始featured是null,页面渲染时会尝试访问null[0],直接抛出错误,就算后面数据加载成功了,页面也没法正常更新。
修复方法:
要么把data里的featured初始化为空数组[],要么给模板加个条件判断,避免报错:
<div id="featured"> <!-- 先判断有没有数据,没有就显示加载提示 --> {{ featured.length > 0 ? featured[0].list_featured_text : '加载中...' }} </div>
3. PHP代码有语法错误
你的PHP代码里有两处小错误,会导致接口返回异常:
$result=mysqli_query(...) or die("Connection failed.")末尾少了分号die("Connection failed. ". $conn->conn->error)这里多写了一个conn,应该是$conn->error
修正后的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->error); // 修正错误调用 $conn->query("SET NAMES utf8"); $sql="SELECT * FROM featured"; $result=mysqli_query($conn,$sql) or die("Query failed."); // 添加分号,优化错误提示 $myarray=array(); while($row=mysqli_fetch_assoc($result)) { $myarray[]=$row; } echo json_encode($myarray); $conn->close(); ?>
把这几个问题都修复后,页面应该就能正常显示数据啦!
内容的提问来源于stack exchange,提问作者j.joe
相关产品推荐
相关产品推荐

