feat: AddCoachView改用axios上传 FormData
This commit is contained in:
parent
5ba442561b
commit
0d51dd5e2a
1 changed files with 19 additions and 10 deletions
|
|
@ -4,6 +4,7 @@ import { reactive, ref } from 'vue'
|
||||||
import { useRouter } from 'vue-router'
|
import { useRouter } from 'vue-router'
|
||||||
import { add } from '../mock/coach.js'
|
import { add } from '../mock/coach.js'
|
||||||
import { Plus } from '@element-plus/icons-vue'
|
import { Plus } from '@element-plus/icons-vue'
|
||||||
|
import axios from 'axios'
|
||||||
|
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const formRef = ref(null)
|
const formRef = ref(null)
|
||||||
|
|
@ -11,7 +12,7 @@ const formRef = ref(null)
|
||||||
const coach = reactive({
|
const coach = reactive({
|
||||||
name: " ",
|
name: " ",
|
||||||
sex: 1,
|
sex: 1,
|
||||||
avatar: "",
|
file: "",
|
||||||
remark: ""
|
remark: ""
|
||||||
})
|
})
|
||||||
const rules = {
|
const rules = {
|
||||||
|
|
@ -23,19 +24,27 @@ const rules = {
|
||||||
const addHandler = async () => {
|
const addHandler = async () => {
|
||||||
await formRef.value.validate()
|
await formRef.value.validate()
|
||||||
|
|
||||||
add(coach)
|
const fd = new FormData()
|
||||||
|
for (const key of Object.keys(coach)) {
|
||||||
|
fd.append(key, coach[key])
|
||||||
|
}
|
||||||
|
const response = await axios.post("/api/coach", fd)
|
||||||
|
if (response.status === 200) { // 如果axios请求成功拿到了结果
|
||||||
|
const { code, msg, data } = response.data
|
||||||
|
if (code === 200) {
|
||||||
ElMessage({ type: "success", message: `教练 "${coach.name}" 添加成功` })
|
ElMessage({ type: "success", message: `教练 "${coach.name}" 添加成功` })
|
||||||
|
router.replace("/coach")
|
||||||
|
} else {
|
||||||
|
ElMessage({ type: "error", message: msg })
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ElMessage({ type: "error", message: response.statusText })
|
||||||
|
}
|
||||||
router.replace("/coach")
|
router.replace("/coach")
|
||||||
}
|
}
|
||||||
const uploadChangeHandler = (file, fileList) => {
|
const uploadChangeHandler = (file, fileList) => {
|
||||||
if (fileList.length > 1) { fileList.shift() }
|
if (fileList.length > 1) { fileList.shift() }
|
||||||
const reader = new FileReader()
|
coach.file = file.raw
|
||||||
reader.onload = e => {
|
|
||||||
coach.avatar = e.target.result
|
|
||||||
}
|
|
||||||
reader.readAsDataURL(file.raw)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue