简体   繁体   English

Vuejs 从实例更改组件中的道具值

[英]Vuejs change prop value in component from instance

I want to Change the prop value in a vue component from my vue instance.我想从我的 vue 实例中更改 vue 组件中的 prop 值。

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>

Consider changing the dropzoneOptions to a computed property, like so.考虑将 dropzoneOptions 更改为计算属性,如下所示。

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.查看https://v2.vuejs.org/v2/guide/computed.html以获取有关计算属性和观察者的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM