vue 上傳四種狀態處理
阿新 • • 發佈:2020-12-15
<template> <div> <!-- <p class="text-center">hello world</p> --> <input ref='uploadInput' type= "file" class="dl-none" name="icon" @change="dealfilechange"/> <button class="btn btn-primary" @click="uploadgogo"> <slot name="default" v-if="status==='ready'"> <span>上傳</span> </slot> <span v-if="status==='loading'">上傳中</span> <span v-if="status==='success'">上傳成功</span> <span v-if="status==='error'">上傳失敗</span> </button> </div> </template> file <script lang="ts"> import Vue from 'vue' import axios from 'axios'; import {defineComponent,ref,onMounted,PropType} from "vue" import { conditionalExpression } from '@babel/types'; type uploadStatus = "ready" | "loading" | "success" | "error"; type beforeupload = (file:File)=>boolean export default defineComponent({ props:{ beforeupload2:{ type:Function as PropType<beforeupload> } }, setup(props,context){ const status = ref<uploadStatus>("ready"); const uploadInput = ref<HTMLElement| null>(null); const dealfilechange =(e:Event)=>{ const input = e.target as HTMLInputElement; let files = input.files; let token = localStorage.getItem("token") if(files){ let files2 = Array.from(files); let iscontinue = true; // console.log(files2[0]) if(props.beforeupload2){ const fn = props.beforeupload2 as Function; iscontinue = fn(files2[0]) } // 如果驗證失敗,則不執行上傳的邏輯 if(!iscontinue){ return; } const formdata = new FormData(); formdata.append(files2[0].name,files2[0]); status.value = "loading" axios.post('http://xxxx.com/xxx',formdata,{ headers:{ "Authorization":`Bearer ${token}` } }).then(value=>{ status.value = "success" }).catch(e=>{ status.value = "error" }).finally( ()=>{ setTimeout(()=>{ status.value = "ready" input.value = "" },1000) } ) } } // 上傳課程 const uploadgogo = ()=>{ // console.log(uploadInput.value) let oBtn = uploadInput.value as HTMLInputElement; oBtn.click(); } return { dealfilechange, uploadgogo, uploadInput// 要把這個匯出去,這樣才能夠動態繫結, ,status } } }) </script> <style> .dl-none{ display:none; } </style>
上面就是四種狀態,很簡單,用 v-if 來分別針對不同的狀態顯示不同的介面!
型別的定義,函式的傳遞,都涉及到了,ts 最核心就是型別的寫法!
熟練掌握了,就好多了,剛開始我也不熟練!