Vue2 异步获取的数据(通过ajax)获取的数据 渲染到dom上

时间:2022-02-28 06:31:33

页面dom结构如下

<ul class="user" id="app">
<li><span>姓名: </span> <i id="name">{{msg.name}}</i></li>
<li><span>年龄: </span><i id="old">{{msg.old}}</i></li>
     <li><span>地址: </span><i id="address">{{msg.address}}</i></li>
<li><span>id: </span><i id="user_id">{{msg.user_id}}</i></li>
<li class="del" style="width: 300px;height: 100px;background: yellowgreen;cursor: pointer;">删除</li>
<br /><br />
</ul>

  

js

                var app = new Vue({
el:'#app',
data:{
msg:{
name:'zhangsan',
old:'18',
address:'shanghai',
user_id:'101010',
}
},
                   //可以将渲染数据的操作放在
                  //beforeCreate 、created 、beforeMounted 、 mounted 里面
                  
beforeCreate:function(){
var _this = this;
$.ajax({
type:"get",
url:"http://127.0.1:8888",
async:true,
success:function(data){
_this.msg.name = data[0]['name'];
_this.msg.old = data[0]['age'];
_this.msg.address = data[0]['address'];
_this.msg.user_id = data[0]['id'];
},
error:function(data){ },
}); },
methods:{ },
});