Search code examples
vue.jsvuejs2v-modelvue-props

How to access to v-model in custom component


I know we can use a v-model on a vue custom component to bind the value to parent component by this.$emit(input, e.target.value). Is there any way we can access the v-model with it's initial value?

I already have a upload-button component written. The upload-button uploads files upon the file change and server reuturns a new filename / fileID. And that filename / fileID will emit to the parent component with v-model.

Vue.component('upload-button', {
  props: ['endpoint'],
  data(){
    return ({
      filename: 'filename...'
    })
  },
  template: `<label class="upload-button">
    <input type="file" accept="image/*" @change="fileSelected" hidden>
    <div class="btn btn--outline text--red">
      Choose file
    </div>
    <span>
      {{ filename }}
    </span>
  </label>`,
  methods: {
    fileSelected(e){

      this.filename = e.target.files[0].name;

      var formData = new FormData();
      formData.append('file', e.target.files[0])

      axios.post(endpoint, formData).then(
        res=>{
          if ( res.data.status ){
            this.filename = res.data.fileId;
            this.emitVModel(res.data.fileId);
          }
        }
      )
    },
    emitVModel(id){
      this.$emit('input', id)
    }
  }
})

I am wondering if the file already exist (i.e. the v-model has an inital value). How can I access to the existing filename / fileID.


Solution

  • You can access to the v-model via this.$attrs.value.

    data(){
      return ({
        filename: this.$attrs.value || 'filename...'
      }) 
    }