javascriptvue.jsvuejs2vue-componentfroala

Vue Froala dynamic config options


I'm using Vue Froala to do the image upload using the Froala config options which are basically an object added to the Vue data property. Something like this:

data() {
    return {
        config: {
            imageUploadURL: '/api/image/store',
            imageUploadParam: 'image',
            imageUploadParams: {id: this.id} //this is the dynamic ID
        }
    }
}

When I upload an image and those config options are triggered, the ID that I'm trying to pass is always undefined. I guess it is because when I first load the page, the Vue data properties are initialized at the very beginning and the dynamic ID that I'm retrieving from a prop, is not yet available.

I tried assigning the data property imageUploadParams a computed property that would return the ID but was still undefined

If I use a watcher to assign the ID afterwards, I get null. Here is what I get in the POST code (php)

+request: Symfony\Component\HttpFoundation\ParameterBag {#45
  #parameters: array:1 [
    "id" => null
  ]
}

Any idea?


Solution

  • You could use a watch:

    data() {
      return {
        config: {
          imageUploadURL: '/api/image/store',
          imageUploadParam: 'image',
          imageUploadParams: { id: '' }
        }
      }
    },
    watch: {
      id(value) {
        this.config.imageUploadParams.id = value;
      }
    }
    

    Now whenever id changes, config.imageUploadParams will be set.

    Assigning a variable in JavaScript sets the value at the time of the assignment. Since your id is empty when it's assigned, there's no reference to use later to access future async properties. Assigning a computed won't help for the same reason.

    Using watch for async, and computed for sync is a good general rule

    Edit from chat

    It seems <froala> isn't able to respond to your reactive data and is only using the initial config value. Put a v-if="id" on the component to prevent it from being created until the id is ready:

    <froala v-if="id">