前端利用vue、html编写,利用axios传输前后端信息
1.需求:利用created钩子函数设置vue中的data,其中在created钩子函数中利用了axios获取后端的数据,想要将axios返回的值给data赋值。
存在问题:axios可以获取后端数据并传递给data,但是无法进行渲染,即vue渲染完初始data之后,axios才将后端的数据传递给data。
在此阶段el:"#container"与id="container"连接良好;html中可以获取vue的data(axios传递的后端数据赋值的data);created钩子函数在除axios函数的地方可以完成赋值data的功能。
<script type="text/javascript">
var baseUrl = "http://localhost:8080/";
var vm = new Vue({
el:"#container",
data:{
username:"",
userimg:"",
isLogin:false,
indexImgs:[],
},
created:function(){
// 获取用户姓名,头像和token
//1.cookie方法
var token = getCookieValue("token");
if(token!=null && token !=""){
this.isLogin = true;
this.username = getCookieValue("username");
this.userimg = getCookieValue("userimg");
}
//轮播图数据
var url=baseUrl+"index/indeximg";
var that = this;
axios.get(url).then(res=>{ //axios函数内部
var vo = res.data; //无法完成初始化
this.indexImgs =vo.data; //vue的data
console.log(vm.indexImgs); //
console.log(this.indexImgs);//
}); //
},
});
</script>
解决方法:观察html代码中是否存在未实现的vue函数
我存在的问题是在html中提前声明了一个@click=“toSearch”的vue函数,但是未实现因此添加此函数后上述问题即可解决。在vue中添加如下内容:
methods: {
toSearch() {
console.log(vm.indexImgs);
}
},
2.需求:页面显示商品详情内容
存在问题:页面加载数据时发现从后端获取的内容发生二次渲染,造成显示效果不连贯
解决方法:在vue中提前设置好对用参数,并赋为空值
data:{
isLogin:false,
token:null,
username:"",
productId:"",
product:{
productName:"", //让vue进行初次渲染时有数据显示
soldNum:0
},