fix(components): 标签/专题管理适配 VueCropper 组件

This commit is contained in:
ronger 2024-03-22 22:40:55 +08:00
parent aceb025a7d
commit 14d4ef2dc7
4 changed files with 112 additions and 238 deletions

View File

@ -17,74 +17,9 @@
<el-input v-model="tag.tagUri"></el-input> <el-input v-model="tag.tagUri"></el-input>
</el-form-item> </el-form-item>
<el-form-item label="图标"> <el-form-item label="图标">
<el-upload
class="avatar-uploader"
:action="tokenURL.URL"
:multiple="true"
:with-credentials="true"
:headers="uploadHeaders"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="tagIconPath" class="tag-brand-img" :src="tagIconPath">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<el-row> <el-row>
<el-col :span="24"> <el-col :span="24">
<vue-cropper <img @click="cropperVisible=true" :src="tag.tagIconPath" style="width: 80px;height: 80px"/>
ref="cropper"
:aspect-ratio="1 / 1"
:src="tagIconPath"
:checkCrossOrigin="false"
:checkOrientation="false"
:imgStyle="{width: '480px', height: '480px'}"
:autoCropArea="1"
:autoCrop="autoCrop"
preview=".preview"
/>
</el-col>
<el-col :span="24" style="margin-top: 2rem;">
<el-col :span="8">
<el-card>
<div class="card-body d-flex flex-column">
<el-col :span="4" style="text-align: right;">
<div v-if="tagIconPath" class="preview preview-large topic-brand-img"/>
<el-image v-else class="topic-brand-img"/>
</el-col>
<el-col :span="20">
<el-col>
<el-col>
<el-link rel="nofollow" :underline="false">
<h4>{{ tag.tagTitle }}</h4>
</el-link>
</el-col>
<el-col>
<div class="text-muted article-summary-md">{{ tag.tagDescription }}</div>
</el-col>
</el-col>
</el-col>
</div>
</el-card>
</el-col>
</el-col>
<el-col :span="24" style="margin-top: 2rem;">
<el-upload
class="avatar-uploader"
action=""
:multiple="true"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<div>
<el-button type="primary" round plain>上传</el-button>
</div>
</el-upload>
<el-button style="margin-top: 1rem;" type="primary" round plain @click.prevent="reset">重置</el-button>
<el-button type="primary" round plain @click.prevent="cropImage">裁剪</el-button>
<el-col>
<span style="color: red;padding-right: 5px;">*</span>
<span>上传图片调整至最佳效果后,请点击裁剪按钮截取</span>
</el-col>
</el-col> </el-col>
</el-row> </el-row>
</el-form-item> </el-form-item>
@ -114,6 +49,7 @@
</el-form-item> </el-form-item>
</el-form> </el-form>
</el-col> </el-col>
<ImgCropper @onSubmit="updateTagIcon" :visible.sync='cropperVisible' :avatarUrl="tagIconPath || ''"></ImgCropper>
</el-row> </el-row>
</template> </template>
@ -122,14 +58,15 @@ import Vue from "vue";
import {mapState} from 'vuex'; import {mapState} from 'vuex';
import VueCropper from "vue-cropper"; import VueCropper from "vue-cropper";
import apiConfig from '~/config/api.config'; import apiConfig from '~/config/api.config';
import ImgCropper from "~/components/ImgCropper.vue";
export default { export default {
name: "PostTag", name: "PostTag",
middleware: 'auth', middleware: 'auth',
components: { components: {
VueCropper VueCropper, ImgCropper
}, },
validate({params, store}) { validate({params}) {
if (typeof params.tag_id === 'undefined') { if (typeof params.tag_id === 'undefined') {
return true; return true;
} }
@ -145,7 +82,8 @@ export default {
...mapState({ ...mapState({
uploadHeaders: state => { uploadHeaders: state => {
return {'X-Upload-Token': state.uploadHeaders} return {'X-Upload-Token': state.uploadHeaders}
} },
tagInfo: state => state.tag.detail.data
}) })
}, },
data() { data() {
@ -155,15 +93,23 @@ export default {
linkToImageURL: '', linkToImageURL: '',
token: '' token: ''
}, },
tag: {},
tagIconPath: '', tagIconPath: '',
loading: false, loading: false,
isEdit: false, isEdit: false,
tag: {},
autoCrop: true, autoCrop: true,
cropperVisible: false,
notificationFlag: true notificationFlag: true
} }
}, },
methods: { methods: {
updateTagIcon(data) {
this.tag.tagIconPath = data
this.tagIconPath = data
this.tag.tagImageType = '1'
this.cropperVisible = false
},
_initEditor(data) { _initEditor(data) {
let _ts = this; let _ts = this;
@ -255,52 +201,15 @@ export default {
placeholder: data.placeholder, placeholder: data.placeholder,
}) })
}, },
handleAvatarSuccess(res) {
let _ts = this;
if (res && res.data && res.data.url) {
let tag = _ts.tag;
tag.tagIconPath = res.data.url;
_ts.$set(_ts, 'tag', tag);
_ts.$set(_ts, 'tagIconPath', res.data.url);
} else {
_ts.$message.error('上传失败!');
}
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isPNG = file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!(isJPG || isPNG)) {
this.$message.error('上传图标只能是 JPG 或者 PNG 格式!');
return false;
}
if (!isLt2M) {
this.$message.error('上传图标大小不能超过 2MB!');
return false;
}
this.fileToBase64(file);
return false;
},
fileToBase64(file) {
let _ts = this;
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
_ts.$set(_ts, 'tagIconPath', this.result);
_ts.$refs.cropper.replace(this.result);
}
},
async updateTag() { async updateTag() {
let _ts = this; let _ts = this;
_ts.$set(_ts, 'loading', true); _ts.$set(_ts, 'loading', true);
let tag = _ts.tag; let tag = _ts.tag;
let id = tag.idTag; let id = tag.idTag;
let tagContent = _ts.contentEditor.getValue(); let tagDescription = _ts.contentEditor.getValue();
let tagContentHtml = await _ts.contentEditor.getHTML(); let tagDescriptionHtml = await _ts.contentEditor.getHTML();
tag.tagDescription = tagContent; tag.tagDescription = tagDescription;
tag.tagDescriptionHtml = tagContentHtml; tag.tagDescriptionHtml = tagDescriptionHtml;
let title = id ? '更新' : '添加'; let title = id ? '更新' : '添加';
_ts.$axios[id ? '$put' : '$post']('/api/admin/tag/post', tag).then(function (res) { _ts.$axios[id ? '$put' : '$post']('/api/admin/tag/post', tag).then(function (res) {
if (res && res.message) { if (res && res.message) {
@ -318,21 +227,6 @@ export default {
}, },
reset() { reset() {
this.$refs.cropper.reset(); this.$refs.cropper.reset();
},
// get image data for post processing, e.g. upload or setting image src
cropImage() {
let _ts = this;
try {
_ts.cropImg = _ts.$refs.cropper.getCroppedCanvas().toDataURL();
let tag = _ts.tag;
tag.tagIconPath = _ts.cropImg;
_ts.$set(_ts, 'tag', tag);
_ts.$set(_ts, 'tagIconPath', _ts.cropImg);
_ts.$message.success('已裁剪 !');
} catch (e) {
_ts.$message.error('图片获取失败 !');
return;
}
} }
}, },
beforeRouteLeave(to, from, next) { beforeRouteLeave(to, from, next) {
@ -354,7 +248,7 @@ export default {
beforeDestroy() { beforeDestroy() {
window.onbeforeunload = null; window.onbeforeunload = null;
}, },
mounted() { async mounted() {
window.addEventListener('beforeunload', e => { window.addEventListener('beforeunload', e => {
e = e || window.event; e = e || window.event;
@ -367,23 +261,21 @@ export default {
return '关闭提示'; return '关闭提示';
}); });
let _ts = this; let _ts = this;
_ts.$axios.$get('/api/upload/simple/token').then(function (res) { const responseData = await _ts.$axios.$get('/api/upload/simple/token');
if (res) { if (responseData) {
_ts.$store.commit('setUploadHeaders', res.uploadToken); _ts.$store.commit('setUploadHeaders', responseData.uploadToken);
_ts.$set(_ts, 'tokenURL', { _ts.$set(_ts, 'tokenURL', {
token: res.uploadToken || '', token: responseData.uploadToken || '',
URL: res.uploadURL || '', URL: responseData.uploadURL || '',
linkToImageURL: res.linkToImageURL || '' linkToImageURL: responseData.linkToImageURL || ''
}) })
} }
});
let tag = _ts.$store.state.tag.detail.data;
_ts.$set(_ts, 'tag', JSON.parse(JSON.stringify(tag)));
Vue.nextTick(() => { Vue.nextTick(() => {
let tagDescription = ''; let tagDescription = '';
if (_ts.$route.params.tag_id) { if (_ts.$route.params.tag_id) {
let tag = _ts.tagInfo
_ts.$set(_ts, 'tag', JSON.parse(JSON.stringify(tag)));
_ts.$set(_ts, 'isEdit', true); _ts.$set(_ts, 'isEdit', true);
tagDescription = _ts.tag.tagDescription tagDescription = _ts.tag.tagDescription
} else { } else {
@ -404,5 +296,5 @@ export default {
</script> </script>
<style lang="less"> <style lang="less">
@import "~vditor/src/assets/less/index.less"; @import "~vditor/src/assets/less/index.less";
</style> </style>

View File

@ -23,38 +23,13 @@
<el-form-item label="图标"> <el-form-item label="图标">
<el-row> <el-row>
<el-col :span="24"> <el-col :span="24">
<img @click="cropperVisible=true" :src="topicIconPath" style="width: 80px;height: 80px"/> <img @click="cropperVisible = true" :src="topic.topicIconPath" style="width: 80px;height: 80px"/>
</el-col> </el-col>
</el-row> </el-row>
</el-form-item> </el-form-item>
<el-form-item label="描述"> <el-form-item label="描述">
<div id="contentEditor" @blur="blurData"></div> <div id="contentEditor"></div>
</el-form-item> </el-form-item>
<!-- <el-form-item>-->
<!-- <el-row >-->
<!-- <el-col :span="8">-->
<!-- <el-card>-->
<!-- <div class="card-body d-flex flex-column">-->
<!-- <el-card shadow="never">-->
<!-- <div class="card-body d-flex flex-column">-->
<!-- <el-row :gutter="20">-->
<!-- <el-col :span="5" style="text-align: right;">-->
<!-- <img :src="topicIconPath" :alt="topic.topicTitle"-->
<!-- style="display: block;width:60px;height: 60px" class="topic-brand-img">-->
<!-- </el-col>-->
<!-- <el-col :span="18">-->
<!-- <span style="font-size: 18px;font-weight: bold"> {{ topic.topicTitle }}</span>-->
<!-- <div class="text-muted article-summary-md text-content">{{ topic.topicDescription }}</div>-->
<!-- </el-col>-->
<!-- </el-row>-->
<!-- </div>-->
<!-- </el-card>-->
<!-- </div>-->
<!-- </el-card>-->
<!-- </el-col>-->
<!-- </el-row>-->
<!-- </el-form-item>-->
<el-form-item label="导航主题"> <el-form-item label="导航主题">
<el-switch <el-switch
v-model="topic.topicNva" v-model="topic.topicNva"
@ -85,7 +60,7 @@
</el-form-item> </el-form-item>
</el-form> </el-form>
</el-col> </el-col>
<ImgCropper @onSubmit="updateUser" :visible.sync='cropperVisible' :avatarUrl="topicIconPath||''"></ImgCropper> <ImgCropper @onSubmit="updateTopicIcon" :visible.sync='cropperVisible' :avatarUrl="topicIconPath||''"></ImgCropper>
</el-row> </el-row>
</template> </template>
@ -103,11 +78,24 @@ export default {
components: { components: {
VueCropper, ImgCropper VueCropper, ImgCropper
}, },
validate({params}) {
if (typeof params.topic_id === 'undefined') {
return true;
}
return params.topic_id && !isNaN(Number(params.topic_id))
},
asyncData({store, params, error}) {
return Promise.all([
store.dispatch('topic/fetchPostDetail', params)
.catch(err => error({statusCode: 404}))
])
},
computed: { computed: {
...mapState({ ...mapState({
uploadHeaders: state => { uploadHeaders: state => {
return {'X-Upload-Token': state.uploadHeaders} return {'X-Upload-Token': state.uploadHeaders}
} },
topicInfo: state => state.topic.detail.data
}) })
}, },
data() { data() {
@ -140,24 +128,15 @@ export default {
autoCrop: true, autoCrop: true,
notificationFlag: true, notificationFlag: true,
cropperVisible: false, cropperVisible: false,
contentEditor:{} contentEditor: {}
} }
}, },
methods: { methods: {
blurData(){ updateTopicIcon(data) {
console.log(this.contentEditor)
if(this.contentEditor!={}){
console.log(this.contentEditor.getValue())
this.topic.topicDescription=this.contentEditor.getValue();
}
},
updateUser(data) {
this.topic.topicIconPath = data this.topic.topicIconPath = data
this.topicIconPath = data this.topicIconPath = data
this.topic.topicImageType = '1'
this.cropperVisible = false this.cropperVisible = false
}, },
@ -264,6 +243,7 @@ export default {
_ts.$axios[id ? '$put' : '$post']('/api/admin/topic/post', data).then(function (res) { _ts.$axios[id ? '$put' : '$post']('/api/admin/topic/post', data).then(function (res) {
if (res && res.message) { if (res && res.message) {
_ts.$message.error(res.message); _ts.$message.error(res.message);
_ts.$set(_ts, 'loading', false);
} else { } else {
_ts.$message({ _ts.$message({
type: 'success', type: 'success',
@ -271,30 +251,11 @@ export default {
}); });
_ts.$set(_ts, 'loading', false); _ts.$set(_ts, 'loading', false);
_ts.$set(_ts, 'notificationFlag', false); _ts.$set(_ts, 'notificationFlag', false);
_ts.contentEditor.setValue('');
_ts.$router.push({
path: `/admin/topic/${data.topicUri}`
})
} }
}) })
}, },
reset() { reset() {
this.$refs.cropper.reset(); this.$refs.cropper.reset();
},
// get image data for post processing, e.g. upload or setting image src
cropImage() {
let _ts = this;
try {
_ts.cropImg = _ts.$refs.cropper.getCroppedCanvas().toDataURL();
let topic = _ts.topic;
topic.topicIconPath = _ts.cropImg;
_ts.$set(_ts, 'topic', topic);
_ts.$set(_ts, 'topicIconPath', _ts.cropImg);
_ts.$message.success('已裁剪 !');
} catch (e) {
_ts.$message.error('图片获取失败 !');
return;
}
} }
}, },
beforeRouteLeave(to, from, next) { beforeRouteLeave(to, from, next) {
@ -316,7 +277,7 @@ export default {
beforeDestroy() { beforeDestroy() {
window.onbeforeunload = null; window.onbeforeunload = null;
}, },
async mounted() { mounted() {
window.addEventListener('beforeunload', e => { window.addEventListener('beforeunload', e => {
e = e || window.event; e = e || window.event;
@ -339,32 +300,24 @@ export default {
} }
}); });
Vue.nextTick(() => {
if (_ts.$route.params.topic_id) { let topicDescription = '';
_ts.$set(_ts, 'isEdit', true); if (_ts.$route.params.topic_id) {
const responseData = await _ts.$axios.$get('/api/admin/topic/detail/' + _ts.$route.params.topic_id); let topic = _ts.topicInfo
_ts.$set(_ts, 'topic', responseData); _ts.$set(_ts, 'topic', JSON.parse(JSON.stringify(topic)));
if (responseData.topicIconPath) { _ts.$set(_ts, 'isEdit', true);
_ts.$set(_ts, 'topicIconPath', responseData.topicIconPath); topicDescription = _ts.topic.topicDescription;
} else {
_ts.$set(_ts, 'isEdit', false);
} }
} else { _ts.contentEditor = _ts._initEditor({
_ts.$set(_ts, 'isEdit', false); id: 'contentEditor',
} mode: 'both',
height: 300,
let articleContent = ''; placeholder: '', //this.$t('inputContent', this.$store.state.locale)
if (_ts.topic.topicDescription) { resize: false,
articleContent = _ts.topic.topicDescription; value: topicDescription,
} });
_ts.contentEditor = _ts._initEditor({
id: 'contentEditor',
mode: 'both',
height: 300,
placeholder: '', //this.$t('inputContent', this.$store.state.locale)
resize: false,
value: articleContent,
});
setTimeout(()=>{
_ts.contentEditor.blur()
}) })
}, },
@ -372,7 +325,7 @@ export default {
</script> </script>
<style lang="less"> <style lang="less">
@import "~vditor/src/assets/less/index.less"; @import "~vditor/src/assets/less/index.less";
.preview-area { .preview-area {
width: 16rem; width: 16rem;

View File

@ -91,17 +91,8 @@ export const actions = {
}) })
}, },
// 获取文章详情 // 获取详情
fetchPostDetail({ commit }, params = {}) { fetchPostDetail({ commit }, params = {}) {
// const delay = fetchDelay(
// isBrowser
// )
// if (isBrowser) {
// Vue.nextTick(() => {
// window.scrollTo(0, 300);
// })
// }
if (typeof params.tag_id === 'undefined') { if (typeof params.tag_id === 'undefined') {
commit('updateDetailData', getDefaultData()) commit('updateDetailData', getDefaultData())
return; return;

View File

@ -20,6 +20,18 @@ const getDefaultTagsData = () => {
} }
} }
const getDefaultData = () => {
return {
topicTitle: '',
topicIconPath: '',
topicDescription: '',
topicNva: '0',
topicStatus: '0',
topicTagCount: 0,
topicSort: 10
}
}
export const state = () => { export const state = () => {
return { return {
fetching: false, fetching: false,
@ -115,6 +127,32 @@ export const actions = {
commit('updateDetailFetching', false) commit('updateDetailFetching', false)
}) })
}, },
// 获取详情
fetchPostDetail({ commit }, params = {}) {
if (typeof params.topic_id === 'undefined') {
commit('updateDetailData', getDefaultData())
return;
}
commit('updateDetailFetching', true)
// commit('updateDetailData', {})
return this.$axios
.$get(`${ADMIN_API_PATH}/topic/detail/${params.topic_id}`)
.then(response => {
return new Promise(resolve => {
commit('updateDetailData', response)
commit('updateDetailFetching', false)
resolve(response)
// delay(() => {
// resolve(response)
// })
})
})
.catch(error => {
commit('updateDetailFetching', false)
return Promise.reject(error)
})
},
fetchTopicTags({ commit }, params) { fetchTopicTags({ commit }, params) {
commit('updateTopicTagsFetching', true); commit('updateTopicTagsFetching', true);
return this.$axios return this.$axios