[Vuejs]-How to make a link as a file input in vue.js 2?

2👍

I believe there is a small misunderstanding: Vue.js 2 is still javascript. Its goal is not the same as Polymer with its fancy components – it is supposed to enhance JS, not replace it with a different structure altogether.

@David Hallberg Jönsson’s answer will work perfectly fine in Vue.js 2 perfectly fine. If you want it specifically in Vue’s component structure:

<template>
<!-- ... -->
    <a class="fileContainer">
        Click here to trigger the file uploader!
        <input type="file">
    </a>
<!-- ... -->
</template>
<script>
export default {
    props: ['...'],
    data() {
          return {
                ...
          };
    },
    computed:{
        ...
    }
}
</script>
<style>
a.fileContainer {
    overflow: hidden;
    position: relative;
    cursor: pointer;
    display: inline-block;
    color: lightskyblue;
}

a.fileContainer:hover {
  text-decoration: underline;
  color: blue;
}

a.fileContainer > input[type=file] {
    cursor: inherit;
    filter: alpha(opacity=0);
    opacity: 0;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    text-align: right;
}
</style>

If you want to use the programmatic way in your link, it’s not going to be easy because some browsers don’t allow you to trigger click events on input type="file" elements. Your best bet would be to go this way.

(Also, technically you can still use jQuery with Vue, so the code in that link could still work if you wanted it to.)

If you want to know how to handle uploading files, there are many tutorials and some components already pre-made.

0👍

You can actually do this using only CSS, as explained here.

Example (from the link above):

.fileContainer {
    overflow: hidden;
    position: relative;
}

.fileContainer [type=file] {
    cursor: inherit;
    display: block;
    font-size: 999px;
    filter: alpha(opacity=0);
    min-height: 100%;
    min-width: 100%;
    opacity: 0;
    position: absolute;
    right: 0;
    text-align: right;
    top: 0;
}

/* Example stylistic flourishes */

.fileContainer {
    background: red;
    border-radius: .5em;
    float: left;
    padding: .5em;
}

.fileContainer [type=file] {
    cursor: pointer;
}
}
<p>So various methods prevent file upload inputs from being styled conveniently. But that needn't be the case!</p>
<label class="fileContainer">
    Click here to trigger the file uploader!
    <input type="file"/>
</label>

Leave a comment