feat: convert header options component to composition API

This commit is contained in:
IchliebedichZhu 2024-03-07 14:55:05 +00:00
parent df27fad99b
commit 372810e19f
3 changed files with 135 additions and 125 deletions

View File

@ -24,7 +24,7 @@ type TProps = {
percent: number percent: number
text: string text: string
cancelText: string cancelText: string
msg: string msg?: string
} }
type TEmits = { type TEmits = {

View File

@ -13,19 +13,10 @@
</tool-tip> </tool-tip>
</template> </template>
<script lang="ts"> <script lang="ts" setup>
import { defineComponent } from 'vue'
import toolTip from '@/components/common/PopoverTip.vue' import toolTip from '@/components/common/PopoverTip.vue'
export default defineComponent({ const content = '本站为个人项目,所使用素材图片等均为网络收集而来,下载之作品仅供学习研究或欣赏目的而使用,无法提供商用授权哦。'
components: { toolTip },
setup() {
const content = '本站为个人项目,所使用素材图片等均为网络收集而来,下载之作品仅供学习研究或欣赏目的而使用,无法提供商用授权哦。'
return {
content,
}
},
})
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>

View File

@ -6,10 +6,10 @@
* @LastEditTime: 2023-12-11 12:40:59 * @LastEditTime: 2023-12-11 12:40:59
--> -->
<template> <template>
<div class="top-title"><el-input v-model="title" placeholder="未命名的设计" class="input-wrap" /></div> <div class="top-title"><el-input v-model="state.title" placeholder="未命名的设计" class="input-wrap" /></div>
<div class="top-icon-wrap"> <div class="top-icon-wrap">
<template v-if="tempEditing"> <template v-if="tempEditing">
<span style="color: #999; font-size: 14px; margin-right: 0.5rem">{{ stateBollean ? '启用' : '停用' }}</span> <el-switch v-model="stateBollean" @change="stateChange" /> <span style="color: #999; font-size: 14px; margin-right: 0.5rem">{{ state.stateBollean ? '启用' : '停用' }}</span> <el-switch v-model="state.stateBollean" @change="stateChange" />
<div class="divide__line">|</div> <div class="divide__line">|</div>
<el-button plain type="primary" @click="saveTemp">保存模板</el-button> <el-button plain type="primary" @click="saveTemp">保存模板</el-button>
<el-button @click="$store.commit('managerEdit', false)">取消</el-button> <el-button @click="$store.commit('managerEdit', false)">取消</el-button>
@ -18,16 +18,16 @@
<!-- <el-button @click="draw">绘制(测试)</el-button> --> <!-- <el-button @click="draw">绘制(测试)</el-button> -->
<el-button size="large" class="primary-btn" :disabled="tempEditing" @click="save(false)">保存</el-button> <el-button size="large" class="primary-btn" :disabled="tempEditing" @click="save(false)">保存</el-button>
<copyRight> <copyRight>
<el-button :loading="loading" size="large" class="primary-btn" :disabled="tempEditing" plain type="primary" @click="download">下载作品</el-button> <el-button :loading="state.loading" size="large" class="primary-btn" :disabled="tempEditing" plain type="primary" @click="download">下载作品</el-button>
</copyRight> </copyRight>
</div> </div>
<!-- 生成图片组件 --> <!-- 生成图片组件 -->
<SaveImage ref="canvasImage" /> <SaveImage ref="canvasImage" />
</template> </template>
<script lang="ts"> <script lang="ts" setup>
import api from '@/api' import api from '@/api'
import { defineComponent, reactive, toRefs, getCurrentInstance, ComponentInternalInstance } from 'vue' import { reactive, toRefs, defineEmits, defineProps, ref } from 'vue'
import { mapGetters, mapActions, useStore } from 'vuex' import { mapGetters, mapActions, useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import _dl from '@/common/methods/download' import _dl from '@/common/methods/download'
@ -38,62 +38,81 @@ import copyRight from './CopyRight.vue'
import _config from '@/config' import _config from '@/config'
import useConfirm from '@/common/methods/confirm' import useConfirm from '@/common/methods/confirm'
import wGroup from '@/components/modules/widgets/wGroup/wGroup.vue' import wGroup from '@/components/modules/widgets/wGroup/wGroup.vue'
import { useSetupMapGetters } from '@/common/hooks/mapGetters'
export default defineComponent({ type TProps = {
components: { copyRight, SaveImage }, modelValue?: boolean
props: ['modelValue'], }
emits: ['change', 'update:modelValue'],
setup(props, context) { type TEmits = {
const { proxy }: any = getCurrentInstance() as ComponentInternalInstance (event: 'change', data: {downloadPercent: number, downloadText: string}): void
const route = useRoute() (event: 'update:modelValue', data: boolean): void
const router = useRouter() }
const store = useStore()
const state = reactive({ type TState= {
stateBollean: false, stateBollean: boolean,
title: '', title: string,
loading: false, loading: boolean,
}) }
const props = defineProps<TProps>()
const emit = defineEmits<TEmits>()
const route = useRoute()
const router = useRouter()
const store = useStore()
const canvasImage = ref<typeof SaveImage | null>(null)
const {
dPage, dWidgets, tempEditing, dHistory, dPageHistory
} = useSetupMapGetters(['dPage', 'dWidgets', 'tempEditing', 'dHistory', 'dPageHistory'])
const state = reactive<TState>({
stateBollean: false,
title: '',
loading: false,
})
//
async function save(hasCover: boolean = false) {
// Bugs: page proxy?.dPageHistory
if (dHistory.value.length <= 0) {
return
}
store.commit('setShowMoveable', false) //
// console.log(proxy?.dPage, proxy?.dWidgets)
const { id, tempid } = route.query
const cover = hasCover ? await draw() : undefined
const widgets = dWidgets.value // reviseData()
const { id: newId, stat, msg } = await api.home.saveWorks({ cover, id, title: state.title || '未命名设计', data: JSON.stringify({ page: dPage.value, widgets }), temp_id: tempid, width: dPage.value.width, height: dPage.value.height })
stat !== 0 ? useNotification('保存成功', '可在"我的作品"中查看') : useNotification('保存失败', msg, { type: 'error' })
!id && router.push({ path: '/home', query: { id: newId }, replace: true })
store.commit('setShowMoveable', true)
}
//
async function save(hasCover: boolean = false) {
// Bugs: page proxy?.dPageHistory
if (proxy?.dHistory.length <= 0) {
return
}
store.commit('setShowMoveable', false) //
// console.log(proxy?.dPage, proxy?.dWidgets)
const { id, tempid } = route.query
const cover = hasCover ? await proxy?.draw() : undefined
const widgets = proxy.dWidgets // reviseData()
const { id: newId, stat, msg } = await api.home.saveWorks({ cover, id, title: proxy.title || '未命名设计', data: JSON.stringify({ page: proxy.dPage, widgets }), temp_id: tempid, width: proxy.dPage.width, height: proxy.dPage.height })
stat !== 0 ? useNotification('保存成功', '可在"我的作品"中查看') : useNotification('保存失败', msg, { type: 'error' })
!id && router.push({ path: '/home', query: { id: newId }, replace: true })
store.commit('setShowMoveable', true)
}
// //
async function saveTemp() { async function saveTemp() {
const { tempid, tempType: type } = route.query const { tempid, tempType: type } = route.query
let res = null let res = null
if (type == 1) { if (Number(type) == 1) {
// //
if (proxy.dWidgets[0].type === 'w-group') { if (dWidgets.value[0].type === 'w-group') {
const group = proxy.dWidgets.shift() const group = dWidgets.value.shift()
group.record.width = 0 group.record.width = 0
group.record.height = 0 group.record.height = 0
proxy.dWidgets.push(group) dWidgets.value.push(group)
}
// TODO
if (!proxy.dWidgets.some((x) => x.type === 'w-group')) {
alert('提交组件必须为组合!')
return
// proxy.dWidgets.push(wGroup.setting)
}
res = await api.home.saveTemp({ id: tempid, type, title: proxy.title || '未命名组件', content: JSON.stringify(proxy.dWidgets), width: proxy.dPage.width, height: proxy.dPage.height })
} else res = await api.home.saveTemp({ id: tempid, title: proxy.title || '未命名模板', content: JSON.stringify({ page: proxy.dPage, widgets: proxy.dWidgets }), width: proxy.dPage.width, height: proxy.dPage.height })
res.stat != 0 && useNotification('保存成功', '模板内容已变更')
} }
// TODO
if (!dWidgets.value.some((x: Record<string, any>) => x.type === 'w-group')) {
alert('提交组件必须为组合!')
return
// proxy.dWidgets.push(wGroup.setting)
}
res = await api.home.saveTemp({ id: tempid, type, title: state.title || '未命名组件', content: JSON.stringify(dWidgets.value), width: dPage.value.width, height: dPage.value.height })
} else res = await api.home.saveTemp({ id: tempid, title: state.title || '未命名模板', content: JSON.stringify({ page: dPage.value, widgets: dWidgets.value }), width: dPage.value.width, height: dPage.value.height })
res.stat != 0 && useNotification('保存成功', '模板内容已变更')
}
// //
async function stateChange(e: any) { async function stateChange(e: string | number | boolean) {
const { tempid, tempType: type } = route.query const { tempid, tempType: type } = route.query
const { stat } = await api.home.saveTemp({ id: tempid, type, state: e ? 1 : 0 }) const { stat } = await api.home.saveTemp({ id: tempid, type, state: e ? 1 : 0 })
stat != 0 && useNotification('保存成功', '模板内容已变更') stat != 0 && useNotification('保存成功', '模板内容已变更')
@ -103,28 +122,28 @@ export default defineComponent({
return return
} }
// //
if (proxy.title === '自设计模板') { if (state.title === '自设计模板') {
const isPass = await useConfirm('提示', 'PSD自设计作品暂时保存在Github下载可能失败', 'warning') const isPass = await useConfirm('提示', 'PSD自设计作品暂时保存在Github下载可能失败', 'warning')
if (!isPass) { if (!isPass) {
return return
} }
} }
state.loading = true state.loading = true
context.emit('update:modelValue', true) emit('update:modelValue', true)
context.emit('change', { downloadPercent: 1, downloadText: '正在处理封面' }) emit('change', { downloadPercent: 1, downloadText: '正在处理封面' })
await save(true) await save(true)
setTimeout(async () => { setTimeout(async () => {
const { id } = route.query const { id } = route.query
if (id) { if (id) {
const { width, height } = proxy.dPage const { width, height } = dPage.value
context.emit('update:modelValue', true) emit('update:modelValue', true)
context.emit('change', { downloadPercent: 1, downloadText: '准备合成图片' }) emit('change', { downloadPercent: 1, downloadText: '准备合成图片' })
state.loading = false state.loading = false
let timerCount = 0 let timerCount = 0
const animation = setInterval(() => { const animation = setInterval(() => {
if (props.modelValue && timerCount < 75) { if (props.modelValue && timerCount < 75) {
timerCount += RandomNumber(1, 10) timerCount += RandomNumber(1, 10)
context.emit('change', { downloadPercent: 1 + timerCount, downloadText: '正在合成图片' }) emit('change', { downloadPercent: 1 + timerCount, downloadText: '正在合成图片' })
} else { } else {
clearInterval(animation) clearInterval(animation)
} }
@ -132,12 +151,12 @@ export default defineComponent({
await _dl.downloadImg(api.home.download({ id, width, height }) + '&r=' + Math.random(), (progress: number, xhr: any) => { await _dl.downloadImg(api.home.download({ id, width, height }) + '&r=' + Math.random(), (progress: number, xhr: any) => {
if (props.modelValue) { if (props.modelValue) {
clearInterval(animation) clearInterval(animation)
progress >= timerCount && context.emit('change', { downloadPercent: Number(progress.toFixed(0)), downloadText: '图片生成中' }) progress >= timerCount && emit('change', { downloadPercent: Number(progress.toFixed(0)), downloadText: '图片生成中' })
} else { } else {
xhr.abort() xhr.abort()
} }
}) })
context.emit('change', { downloadPercent: 100, downloadText: '图片下载中' }) emit('change', { downloadPercent: 100, downloadText: '图片下载中' })
} }
}, 100) }, 100)
} }
@ -145,56 +164,56 @@ export default defineComponent({
return Math.ceil(Math.random() * (max - min)) + min return Math.ceil(Math.random() * (max - min)) + min
} }
return { // ...mapActions(['pushHistory', 'addGroup']),
...toRefs(state),
download, async function load(id: number, tempId: number, type: number, cb: () => void) {
save, if (route.name !== 'Draw') {
saveTemp, await useFontStore.init() //
stateChange, }
const apiName = tempId && !id ? 'getTempDetail' : 'getWorks'
if (!id && !tempId) {
cb()
return
}
const { data: content, title, state, width, height } = await api.home[apiName]({ id: id || tempId, type })
if (content) {
const data = JSON.parse(content)
state.stateBollean = !!state
state.title = title
store.commit('setShowMoveable', false) //
// this.$store.commit('setDWidgets', [])
if (type == 1) {
//
dPage.value.width = width
dPage.value.height = height
store.dispatch('addGroup', data)
// addGroup(data)
} else {
store.commit('setDPage', data.page)
id ? store.commit('setDWidgets', data.widgets) : store.dispatch('setTemplate', data.widgets)
} }
}, cb()
computed: { store.dispatch('pushHistory', '请求加载load')
...mapGetters(['dPage', 'dWidgets', 'tempEditing', 'dHistory', 'dPageHistory']), // pushHistory('load')
}, }
methods: { }
...mapActions(['pushHistory', 'addGroup']),
async load(id: any, tempId: any, type: any, cb: Function) { function draw() {
if (this.$route.name !== 'Draw') { return new Promise((resolve) => {
await useFontStore.init() // if (!canvasImage.value) resolve('')
} else {
const apiName = tempId && !id ? 'getTempDetail' : 'getWorks' canvasImage.value.createCover(({ key }: {key: string}) => {
if (!id && !tempId) { resolve(_config.IMG_URL + key)
cb()
return
}
const { data: content, title, state, width, height } = await api.home[apiName]({ id: id || tempId, type })
if (content) {
const data = JSON.parse(content)
this.stateBollean = !!state
this.title = title
this.$store.commit('setShowMoveable', false) //
// this.$store.commit('setDWidgets', [])
if (type == 1) {
//
this.dPage.width = width
this.dPage.height = height
this.addGroup(data)
} else {
this.$store.commit('setDPage', data.page)
id ? this.$store.commit('setDWidgets', data.widgets) : this.$store.dispatch('setTemplate', data.widgets)
}
cb()
this.pushHistory('请求加载load')
}
},
draw() {
return new Promise((resolve) => {
this.$refs.canvasImage.createCover(({ key }) => {
resolve(_config.IMG_URL + key)
})
}) })
}, }
}, })
}
defineExpose({
download,
save,
saveTemp,
stateChange,
}) })
</script> </script>