[Vuejs]-Document.querySelector causing errors on other methods when called

2👍

Problems:

You put your input inside the label tag. I learned this is okay.

  1. Why using a button outside the whole label and input tags? I don’t understand what your intention was with that.
  2. You replace the inside of the label tag by a text node (containing the file name). Through your replacement you delete your input field out of the DOM. See querySelector line in your code.
  3. After having replaced the input field, there is no fileName on the page anymore, so it getElementById results in null.

Solution:

  1. (optionally) I’d delete the button tag and only keep the inside of it.
  2. Don’t operate on that label and don’t try to overwrite the value of a file input field
  3. By not removing the input field anymore, you can access it and read out the file name

See my example here: https://stackblitz.com/edit/js-fdxxnf

1👍

You can try with ref:

new Vue({
  el: '#demo',
  data() {
    return {
      projectFile: true
    }
  },
  methods: {
    changeLbl() {
      this.$refs.lab.innerText = 'filename'
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div class="row">
      <div class="clg6 cmd8 csm10 cxs12" v-if="projectFile">
        <button 
          class="button primary outline medium upload">
          <label ref="lab">
            <input 
            type="file"
            name="projectFile"
            id="fileName"
            accept=".xls, .xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" 
            v-on:change="changeLbl"/>
              <i class="fas fa-cloud-upload"></i> 
              Upload Project File
          </label>
        </button>
      </div>
  </div>
</div>

Leave a comment