使用Vue 自定義檔案選擇器元件
阿新 • • 發佈:2020-09-22
檔案選擇元素是web上最難看的input型別之一。它們在每個瀏覽器中實現的方式不同,而且通常非常難看。這裡有一個解決辦法,就是把它封裝成一個元件。
安裝
如果你尚未設定專案,可以使用vue-cli的webpack-simple模板啟動一個新專案。
$ npm install -g vue-cli
$ vue init webpack-simple ./file-upload # Follow the prompts.
$ cd ./file-upload
$ npm install # or yarn
元件模板和樣式
該元件主要做的就是將input type=”file”元素包裝在標籤中,並在其中顯示其他內容,這種思路雖然簡單,便卻很實用。
// 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>
現在來加一些樣式美化一下:
// 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來封裝,讓該元件像普通表單元素一樣。我們知道 v
我們知道, Vue 是單項資料流,v-model只是語法糖而已,如下所示:
<input v-model="sth" />
// 上面等價於下面
<input v-bind:value="sth" v-on:input="sth = $event.target.value" />
知道了 v-model 的原理,我們來實現一下 FileSelect 元件的邏輯:
// 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元件
// 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>
廣州vi設計http://www.maiqicn.com 辦公資源網站大全https://www.wode007.com
總結
雖然該事例很簡單也很基礎,但我們可以在這之上完善更強大的功能,在開發中,單向資料流雖然簡單且易讀,但在一些實際的開發中,Vue 的自定義元件,使用雙向繫結也就是 v-model 的方式,會更加靈活實用,
我們需要了解及掌握這種思路,希望對大家有所幫助。