Vue JS通过链接到组件传递数据

时间:2019-01-19 00:49:38

标签: vue.js vuejs2

在组件中,我有一个选择输入。根据选择的内容,显示上载输入。

<div class="form-group">
    <select class="custom-select" id="uploadType" v-model="uploadType">
        <option value="">Please select...</option>
        <option value="1">Image</option>
        <option value="2">PDF</option>
        <option value="3">Text</option>
    </select>
</div>
<div class="form-group" v-if="uploadType == '1'">
    <uploader :options="options" ref="uploader" file-success="fileSuccess" @file-error="fileError">
        <uploader-drop>
            <uploader-btn :attrs="attrs1" :single=true>select files</uploader-btn>
        </uploader-drop>
    </uploader>
</div>
<div class="form-group" v-if="uploadType == '2'">
    <uploader :options="options" ref="uploader" @file-success="fileSuccess" @file-error="fileError">
        <uploader-drop>
            <uploader-btn :attrs="attrs2" :multiple=true>select files</uploader-btn>
        </uploader-drop>
    </uploader>
</div>
<div class="form-group" v-if="uploadType == '3'">
    <uploader :options="options" ref="uploader" @file-success="fileSuccess" @file-error="fileError">
        <uploader-drop>
            <uploader-btn :attrs="attrs3" :single=true>select files</uploader-btn>
        </uploader-drop>
    </uploader>
</div>

<script>
    import uploader from 'vue-simple-uploader'

    export default {
        data() {
            return {
                uploadType: '',
                options: {
                    target: 'upload'
                },
                attrs1: {
                    accept: '.jpg'
                },
                attrs2: {
                    accept: '.pdf'
                },
                attrs3: {
                    accept: '.txt'
                }
            }
        },
        methods: {
            fileSuccess (rootFile, file, message) {
                console.log(message)
            },
            fileError (rootFile, file, message) {
                console.log(message)
            }
        }
    }
</script>

现在显然那是一团糟,我在重复不好的代码。而且,不再真正需要选择。相反,在另一个页面中,我有这样的链接

<router-link to="/uploadFile" tag="a" class="btn navbar-btn" exact>
    Upload Image
</router-link>

<router-link to="/uploadFile" tag="a" class="btn navbar-btn" exact>
    Upload PDF
</router-link>

<router-link to="/uploadFile" tag="a" class="btn navbar-btn" exact>
    Upload Text
</router-link>

我想尝试的是通过单击的链接发送类型(图像,pdf或文本)。然后,在上载组件中,我可以通过某种方式将其动态设置为uploadType。我会 还需要使第二次上传允许倍数,以及更改可接受的类型。

有什么办法可以通过链接做到这一点?很难解释,但是我基本上是在尝试使我的上载组件可重用。我几乎需要道具之类的东西,但需要链接吗?

谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用$route.params,有关更多信息,请查看Vue router documentation

<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>