can not change data in the @change vuejs handler

2019-08-27 22:23发布

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条回答
Fickle 薄情
2楼-- · 2019-08-27 23:06

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>

查看更多
登录 后发表回答