can not change data in the @change vuejs handler

核能气质少年 提交于 2019-12-11 16:44:10

问题


There is a component that contains input[type=file]. Also, this field has an uploadFile handler, which calls the validateMessage method, which attempts to change the error. As you can see, after changing this.error it shows that everything is correct. But in div.error it is not displayed and if you look in vueDevtool, then there is also empty. data in vueDevTools

data() {
  return {
   error: ''
  }
},
   
methods: {

 validateFile(file) {
   if (! file.type.includes('video/')) {
     this.error = 'wrong format';
     console.log(this.error); // wrong format
   }
 },
 
 uploadFile(e) {
   const file = e.target.files[0];
   this.validateFile(file);
 },
}
<input type="file" 
       id="im_video" 
       name="im_video" 
       @change="uploadFile"
       class="hidden">
           
<div class="error">
  {{ error }}
</div>

回答1:


Here is working example.

new Vue({
  el:'#app',
  data() {
    return {
     error: ''
    }
  },

  methods: {

   validateFile(file) {
      console.log(file.type);
     if (! file.type.includes('video/')) {
       this.error = 'wrong format';
       //console.log(this.error); // wrong format
     }
   },

   uploadFile(e) {
     this.error = '';
     const file = e.target.files[0];
     this.validateFile(file);
   },
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <input type="file" 
         id="im_video" 
         name="im_video" 
         @change="uploadFile"
         class="hidden">

  <div class="error">
    {{ error }}
  </div>
</div>

If you are using component this would help more to share data from child to parent in your case setting error from child component to parent

Vue.component('upload-file',{
  template:`<div><input type="file" 
         id="im_video" 
         name="im_video" 
         @change="uploadFile"
         class="hidden"></div>`,
  data() {
    return {
     error: ''
    }
  },

  methods: {
   validateFile(file) {
      //
     if (! file.type.includes('video/')) {
       vm.$emit('filerror', 'wrong format');
     }
   },

   uploadFile(e) {
    vm.$emit('filerror', '');
     const file = e.target.files[0];
     this.validateFile(file);
   },
  }
});
const vm = new Vue({
  el:'#app',
  mounted(){
    this.$on('filerror', function (msg) {
      this.error = msg;
    })
  },
  data:{
    error:''
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <upload-file></upload-file>
  <div class="error">
    {{ error }}
  </div>
</div>


来源:https://stackoverflow.com/questions/50618269/can-not-change-data-in-the-change-vuejs-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!