Skip to content

Commit

Permalink
上传组件基本功能的实现
Browse files Browse the repository at this point in the history
  • Loading branch information
RenektonChr committed Dec 14, 2020
1 parent 89570fa commit 0faa66d
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 1 deletion.
73 changes: 73 additions & 0 deletions src/components/Upload/index.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<template>
<div class="file-upload">
<button class="btn btn-primary" @click.prevent="triggerUoload">
<span v-if="fileStatus === 'loading'">正在上传...</span>
<span v-else-if="fileStatus === 'success'">上传成功</span>
<span v-else>点击上传</span>
</button>
<input
type="file"
class="file-input d-none"
ref="fileInput"
@change="handleFileChange"
>
</div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import axios from 'axios'
type UploadStatus = 'ready' | 'loading' | 'success' | 'error'
export default defineComponent({
props: {
action: {
type: String,
required: true
}
},
setup (props) {
const fileInput = ref<null | HTMLElement>(null)
const fileStatus = ref<UploadStatus>('ready')
const triggerUoload = () => {
if (fileInput.value) {
fileInput.value.click()
}
}
const handleFileChange = (e: Event) => {
const currentTarget = e.target as HTMLInputElement
if (currentTarget.files) {
fileStatus.value = 'loading'
const files = Array.from(currentTarget.files)
const formData = new FormData()
formData.append('file', files[0])
axios.post(props.action, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(result => {
console.log('result ----->', result.data)
fileStatus.value = 'success'
}).catch(e => {
console.log('error--->', e)
fileStatus.value = 'error'
}).finally(() => {
if (fileInput.value) {
const fileInputEle = fileInput.value as HTMLInputElement
fileInputEle.value = ''
}
})
}
}
return {
fileInput,
triggerUoload,
fileStatus,
handleFileChange
}
}
})
</script>

<style>
</style>
5 changes: 4 additions & 1 deletion src/view/Home/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
</div>
</div>
</section>
<upload action="/upload"></upload>
<h4 class="font-weight-bold text-center">发现精彩</h4>
<column-list :list="list"></column-list>
</div>
Expand All @@ -21,10 +22,12 @@ import { defineComponent, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { GlobalDataProps } from '../../store/index'
import ColumnList from '../../components/ColumnList/index.vue'
import Upload from '../../components/Upload/index.vue'
export default defineComponent({
components: {
ColumnList
ColumnList,
Upload
},
setup () {
const store = useStore<GlobalDataProps>()
Expand Down

0 comments on commit 0faa66d

Please sign in to comment.