<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
</head>
<body>
<div id="data">{{datas}}</div>
<script type="text/javascript">
new Vue({
el:'#data',
data:{
datas:null
},
mounted:function(){
const params = new URLSearchParams();
params.append('type', 'queryHeadCarousel');
axios
.post('https://xxxx/php.php',params)
.then(function(response){
this.datas = response;
console.log(this.datas);
})
.catch(function (error) { // 请求失败处理
console.log(error);
})
}
})
</script>
</body>
</html>
我在mounted周期中访问数据接口并取得数据对象,并赋给datas,此时控制台打印datas含有数据,但是在dom中访问{{datas}}却为空?
初学vue,各位能不能帮忙解解惑?
//////////////////////////////
找到原因了,下面第一种写法就行,第二种就不行。
弱弱问一句有啥区别吗?0.0
第一种:
.then(response => (this.datas= response.data))
第二种:
.then(function(response){
this.datas = response.data;
})
response.data
对于 vue 实例上的数据,赋予如字符串或数字的值是没问题的。
但如果要赋予对象值,你需要使用
Vue.set
:{{ var }}
这样的格式只能打印 字符串 (或数字),请确保你的datas
是字符串才能正确输出。function 的 scope 不正确,如果你使用「function () {}」 这样来定义闭包的话,在闭包内的
this
会是闭包本身。如果你想要使用与闭包当前上下文相同的this
的话,需要使用 arrow function (箭头函数),或是指定这个this
给其他变量:使用 function
使用 Arrow function
定义一个 that