使用Vue 自定義文件選擇器組件(基礎雖簡單,但思路咱們要掌握)

點贊再看,養成習慣

本文 GitHub https://github.com/qq44924588... 上已經收錄,更多往期高贊文章的分類,也整理了不少個人文檔,和教程資料。歡迎Star和完善,你們面試能夠參照考點複習,但願咱們一塊兒有點東西。前端

文件選擇元素是web上最難看的 input 類型之一。它們在每一個瀏覽器中實現的方式不一樣,並且一般很是難看。這裏有一個解決辦法,就是把它封裝成一個組件。vue

安裝

若是你還沒有設置項目,可使用vue-cliwebpack-simple模板啓動一個新項目。webpack

$ npm install -g vue-cli
$ vue init webpack-simple ./file-upload # Follow the prompts.
$ cd ./file-upload
$ npm install # or yarn

組件模板和樣式

該組件主要作的就是將input type=」file」元素包裝在標籤中,並在其中顯示其餘內容,這種思路雖然簡單,便卻很實用。git

// FileSelect.vue

<template>
  <label class="file-select">
    <div class="select-button">
      <span v-if="value">Selected File: {{value.name}}</span>
      <span v-else>Select File</span>
    </div>
    <input type="file" @change="handleFileChange"/>
  </label>
</template>

如今來加一些樣式美化一下:github

// FileSelect.vue
...
<style scoped>
.file-select > .select-button {
  padding: 1rem;

  color: white;
  background-color: #2EA169;

  border-radius: .3rem;

  text-align: center;
  font-weight: bold;
}

/* Don't forget to hide the original file input! */
.file-select > input[type="file"] {
  display: none;
}
</style>

封裝邏輯

對於瀏覽器來講,file是一種很是特殊的類型,因此有一些特殊的規則使它們有時很難處理。(更多信息請點擊這裏)。所以,咱們能夠藉助 v-model來封裝,讓該組件像普通表單元素同樣。咱們知道 vweb

咱們知道, Vue 是單項數據流,v-model 只是語法糖而已,以下所示:面試

<input v-model="sth" />
// 上面等價於下面
<input v-bind:value="sth" v-on:input="sth = $event.target.value" />

知道了 v-model 的原理,咱們來實現一下 FileSelect 組件的邏輯:vue-cli

// FileSelect.vue 
<script>
export default {
  props: {
    // 這裏接受一個 value 由於 v-model 會給組件傳遞一個 value 屬性
    value: File
  },

  methods: {
    handleFileChange(e) {
      // 一樣觸發一個 input 來配合 v-model 的使用
      this.$emit('input', e.target.files[0])
    }
  }
}
</script>

用法

如今,咱們來用下 FileSelect 組件npm

// App.vue
<template>
  <div>
    <p>選擇文件: <file-select v-model="file"></file-select></p>
    <p v-if="file">{{file.name}}</p>
  </div>
</template>

<script>
import FileSelect from './FileSelect.vue'

export default {
  components: {
    FileSelect
  },

  data() {
    return {
      file: null
    }
  }
}
</script>

總結

雖然該事例很簡單也很基礎,但咱們能夠在這之上完善更強大的功能,在開發中,單向數據流雖然簡單且易讀,但在一些實際的開發中,Vue 的自定義組件,使用雙向綁定也就是 v-model 的方式,會更加靈活實用,
咱們須要瞭解及掌握這種思路,但願對你們有所幫助。bootstrap

下節會在公衆號發佈對應的視頻教程,敬請關注。


代碼部署後可能存在的BUG無法實時知道,過後爲了解決這些BUG,花了大量的時間進行log 調試,這邊順便給你們推薦一個好用的BUG監控工具 Fundebug

做者:Joshua Bemenderfer 譯者:前端小智 來源:codepen
原文:https://bootstrap-vue.js.org/...


交流

文章每週持續更新,能夠微信搜索「 大遷世界 」第一時間閱讀和催更(比博客早一到兩篇喲),本文 GitHub https://github.com/qq449245884/xiaozhi 已經收錄,整理了不少個人文檔,歡迎Star和完善,你們面試能夠參照考點複習,另外關注公衆號,後臺回覆福利,便可看到福利,你懂的。

相關文章
相關標籤/搜索