Home > Enterprise >  Vue.js component isn't updated after parent changes boud data field
Vue.js component isn't updated after parent changes boud data field

Time:04-23

I have roughly the following:

<template>
  <header>
    <h1>Toolbox</h1>
  </header>

  <main>
    <Info :file_data="file_data" v-if="file_loaded"/>
    <DropArea @file-dropped="onDrop"/>
  </main>
</template>

<script>
import DropArea from './components/DropArea.vue'
import Info from './components/Info.vue'

export default {
  name: 'Toolbox',
  components: {
    DropArea,
    Info,
  },
  data() {
    return {
      file_loaded: false,
      reader: new FileReader(),
      file_data: new Uint8Array(),
    }
  },
  methods: {
    onDrop(file) {    
      this.reader.onloadend =this.onFileLoaded;
      this.reader.readAsArrayBuffer(file);
    },
    onFileLoaded(file_data) {
      this.file_loaded = true
      this.file_data = new Uint8Array(this.reader.result); //this should update the property on the Info Component
    }
  }
}
</script>

The Info Component uses a property and watches it like this:

<script>
export default {
name: 'Info',
props: ['file_data'],
watch: {
    file_data: 'onFileDataChanged'
},
methods: {
    onFileDataChanged() {
        console.log('file_data changed')
    }
},
}
</script>

Unfortunately this doesn't work for the first dropped file. Only from the second file onwards, it works. Can someone tell me what I'm doing wrong?

Thx Tobias

CodePudding user response:

By default, watchers only watch on updates to the value. To have it call on the initial value as well, set immediate: true with the object syntax.

Docs

<script>
export default {
  name: 'Info',
  props: ['file_data'],
  watch: {
    file_data: {
      handler: 'onFileDataChanged',
      immediate: true
    }
  },
  methods: {
   onFileDataChanged() {
      console.log('file_data changed')
    }
  },
}
</script>
  • Related