解決vue data 更新而檢視沒有更新的情況
今天碰到一個大為頭疼的問題,用this.data 賦值,控制檯顯示值改變了,但是檢視就是沒有更新,查了各種辦法,網上說是因為給陣列 賦值檢測不到,而我的是一個字串物件好嘛,上程式碼看下
html部分:
<div class="ch-col ui-col-70"> <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/" :http-request="upload" :on-change='changeFile' :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"> <img v-if="imageUrl" ref="img" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload>
</div>
js 部分:
var vm= new Vue({ el:"#app", data:{ imageUrl:'', fileImage:'', title:0 }, methods:{ click:e=>{
vm.$set(vm.$data,'title',999); vm.$data.title='888'; console.log(this.title); }, handleAvatarSuccess:function(res,file){ this.imageUrl = URL.createObjectURL(file.raw); }, beforeAvatarUpload:function(file){ const isJPG = file.type === 'image/jpeg'; const isLt2M = file.size / 1024 / 1024 < 2; this.fileImage=file; return isJPG && isLt2M; }, upload:file=>{ return false; }, changeFile: (file,fileList)=>{ var self=this; const isLt2M = file.size / 1024 / 1024 < 2; if (!isLt2M) { this.$message.error('上傳頭像圖片大小不能超過 2MB!'); } var imgfile= URL.createObjectURL(file.raw); this.imageUrl=imgfile; this.fileImage=file; }, commit:res=>{ var self=this; console.log(self.fileImage); $.ajax({ url:'www.baidu.com', data:{ file:self.fileImage }, success:function(){
} }) } } });
this.imageUrl=imgfile; 控制檯能清楚的看出change裡面this.imageUrl已經修改然而檢視就是沒有更新。。。。
解決辦法;this.imageUrl=imgfile; 改成 vm.$data.imageUrl=imgfile;
完美解決,另外,vm.$data.imageUrl可以簡寫成vm.imageUrl;
還有一個很神奇的事情
console.log(vm.imageUrl==this.imageUrl);
你猜是true還是false?
答案是:
具體原因我也不知道為啥,誰能告訴我