tigerel
tigerel

Reputation: 337

Vuejs change prop value in component from instance

I want to Change the prop value in a vue component from my vue instance.

So that I can use the title value inside my component.

The component:

<template>
    <vue-dropzone ref="uploadDropzone" id="dropzone" :options="dropzoneOptions" :title="title"></vue-dropzone>
</template>

<script>
import vue2Dropzone from 'vue2-dropzone'
import 'vue2-dropzone/dist/vue2Dropzone.css'

export default {
    name: 'app',

    components: {
        vueDropzone: vue2Dropzone
    },

    props: ['title'], // title shall update so that I can use the value as a param below

    data () {
        return {
            dropzoneOptions: {
                method: 'post',
                title: this.title
            }
        }
    },
}
</script>

The instance in which I Change the title value:

Vue.component('vue-dropzone', require('./components/ImageDropzoneComponent.vue'));

const app = new Vue({
    el: '#app',

    data: {
        title: '',
    },

    methods: {
        foo (e) {
            console.log(this.title); // has correct value but how to pass to vue component (prop)
        },
    }
});


<vue-dropzone ref="uploadDropzone" :title="title"></vue-dropzone>

Upvotes: 1

Views: 2528

Answers (1)

dennythecoder
dennythecoder

Reputation: 772

Consider changing the dropzoneOptions to a computed property, like so.

import vue2Dropzone from 'vue2-dropzone'
import 'vue2-dropzone/dist/vue2Dropzone.css'

export default {
    name: 'app',

    components: {
        vueDropzone: vue2Dropzone
    },

    props: ['title'], // title shall update so that I can use the value as a param below

    computed:
        dropZoneOptions() { // dropZoneOptions recomputes when props.title changes
            return {
                method: 'post',
                title: this.title
            }
        }
    },
}

Alternatively, you may consider a watcher and modify the data on a change, but with the original code posted, I believe this may be the best route.

Check out https://v2.vuejs.org/v2/guide/computed.html for info on both computed properties and watchers.

Upvotes: 1

Related Questions