LoginSignup
31
18

More than 3 years have passed since last update.

Vue.jsでinputタグを表示せずに任意のボタン押下でファイル選択DLGを表示させる

Last updated at Posted at 2019-06-12

はじめに

vue.jsに限ったことではありませんが、UIフレームワークを使用していて、標準のinputタグを配置すると見た目が統一できない(ブラウザによって変わる、UIフレームワークの見た目と統一性がない)点が気になるかと思います。

そこでinputタグを直接使用せずにファイルの選択ダイアログを表示させます。

左:通常のinputタグを用いた場合
右:inputタグを用いない場合
btnsample.png

コード

※vuetifyを使用していますが、(v-xタグ)今回の説明と直接は関係は関係ありません。
他のフレームワークの場合、v-btnはそのフレームワーク等のボタンに置き換えてください。

sample.vue
<template>
  <v-container>
    // 非表示のinputタグを格納
    <input
      style="display: none"
      ref="input"
      type="file"
      accept="image/jpeg, image/jpg, image/png"
      @change="selectedFile()"
    >
    <v-layout text-xs-center wrap>
      // 略
      <v-flex xs12>
        <!-- ファイルの選択 -->
        <v-btn color="primary" @click="btnclick">select image</v-btn>
      </v-flex>
      // 略
    </v-layout>
  </v-container>
</template>
<script>
export default {
  data() {
    return {
      // 略
    };
  },
  methods: {
    // selectfileボタン押下時
    btnclick() {
      this.$refs.input.click();
    },
    async selectedFile() {
      this.isUploading = true;

      const file = this.$refs.input.files[0]
      if (!file) {
        return;
      }
   // 以下ファイルの操作

    }
  }
};
</script>

やり方としては、下記になります。

  1. 非表示のinputタグを配置(refで参照できるようにしておく)
  2. ボタンを配置してクリックイベントで1を参照してclickを呼び出す
31
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
18