123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927 |
- <template>
- <div class="mainBox">
- <div class="layerBox">
- <tableTitle :name="tableDivTitle"/>
- <el-form :model="form" ref="form" :rules="formRules" label-position="left" label-width="120px">
- <div class="formDiv">
- <el-form-item label="发布类型" prop="type_id" class="custom-align-right">
- <el-radio-group v-model="form.type_id" >
- <el-radio :label="1">供应商品</el-radio>
- <el-radio :label="2">求购商品</el-radio>
- </el-radio-group>
- </el-form-item>
- <el-form-item label="商品名称:" prop="name" class="custom-align-right">
- <template #label>
- <span class="askBox" v-if="form.type_id==1">
- 商品名称:
- </span>
- <span class="askBox" v-if="form.type_id==2">
- 标题:
- </span>
- </template>
- <el-input v-model="form.name" autocomplete="off" placeholder="请输入商品标题"></el-input>
- </el-form-item>
- <el-form-item label="发布地点:" prop="city_arr_id" class="custom-align-right">
- <el-cascader :key="cascaderKey" v-model="form.city_arr_id" placeholder="发布地区:" :props="cityData" filterable clearable></el-cascader>
- </el-form-item>
- <el-form-item label="导航池名称:" prop="cat_arr_id" class="custom-align-right">
- <el-cascader :key="parentKey" v-model="form.cat_arr_id" placeholder="请选择要绑定的导航池名称" :props="parentData" filterable clearable></el-cascader>
- </el-form-item>
- <div v-if="form.type_id==1">
- <el-form-item label="商品单价:" prop="price" class="custom-align-right" >
- <el-input v-model="form.price" autocomplete="off" placeholder="请输入商品单价">
- <template #suffix>
- 元
- </template>
- </el-input>
- </el-form-item>
- <el-form-item label="单位:" prop="unit" class="custom-align-right" >
- <el-input v-model="form.unit" autocomplete="off" placeholder="请输入单位"></el-input>
- </el-form-item>
- <el-form-item label="最小定量:" prop="min" class="custom-align-right" >
- <el-input v-model="form.min" autocomplete="off" placeholder="请输入最小定量"></el-input>
- </el-form-item>
- <el-form-item label="供货总量:" prop="max" class="custom-align-right" >
- <el-input v-model="form.max" autocomplete="off" placeholder="请输入供货总量"></el-input>
- </el-form-item>
- <el-form-item label="有效期:" prop="validity" class="custom-align-right">
- <el-date-picker
- v-model="form.validity"
- type="date"
- placeholder="选择日期"
- :disabled="form.islong == 1"
- >
- </el-date-picker>
- <el-checkbox v-model="form.islong" >无期限</el-checkbox>
- </el-form-item>
- </div>
- <div v-if="form.type_id==2">
- <el-form-item label="截止日期:" prop="validity" class="custom-align-right">
- <el-date-picker
- v-model="form.validity"
- type="date"
- placeholder="选择日期"
- :disabled="form.islong == 1"
- >
- </el-date-picker>
- <el-checkbox v-model="form.islong" >无期限</el-checkbox>
- </el-form-item>
- </div>
- <el-form-item label="商品图:" class="custom-align-right" prop="imgurl" >
- <div class="uploaderBox">
- <span v-if="imgurl.length > 0" class="uploaded-images">
- <div v-for="(url, index) in imgurl" :key="index" style="display: inline;float: left; width: 150px;;">
- <img :src="url" class="avatar" style="float: left; margin-right: 10px;">
- <div style="position: relative;
- transform: translate(-50%, -50%);
- right: -120px;
- top: -20px;
- background-color: rgba(0, 0, 0, 0.5);
- color: white;
- border-radius: 50%;
- width: 24px;
- height: 24px;
- display: flex;
- align-items: center;
- justify-content: center;
- cursor: pointer;
- z-index: 10;" @click="deleteImage(index)">
- <i class="el-icon-delete"></i>
- </div>
- </div>
- </span>
- <el-upload class="avatar-uploader1" action="#" :show-file-list="true" :before-upload="beforeAvatarUpload" style="display: inline;">
- <div style="width: 100px; display: inline-block;">
- <img src="@/assets/public/upload/noImage.png" >
- <div>选择图片</div>
- </div>
- </el-upload>
- </div>
- </el-form-item>
- <div class="imgBox" style="margin-left: 100px ;margin-bottom: 20px; padding-top: -20px;">最多可上传5张,每张图片大小不能超过500K,推荐上传图片尺寸 宽1000像素 高1000像素。(首张显示为商品头图)</div>
- <el-form-item label="商品关键词:" prop="keyword" class="custom-align-right">
- <el-input v-model="form.keyword" autocomplete="off" placeholder="请输入商品关键词"></el-input>
- </el-form-item>
- <el-form-item label="商品描述:" prop="description" class="custom-align-right">
- <el-input v-model="form.description" maxlength="300" autocomplete="off" placeholder="请输入商品描述" type="textarea" :rows="10"></el-input>
- </el-form-item>
- <div class="QuillTitle" >
- <span>* </span> <span style="color: #606266" v-if="form.type_id==1">商品详情:</span><span style="color: #606266" v-else>详情说明:</span>
- <div @click="toggleSourceMode" class="QuillModelBtn">
- {{ showHtml ? '切换到编辑模式' : '切换到源码模式' }}
- </div>
- </div>
- <el-form-item label="" prop="detail">
- <div class="editor-container">
- <div v-if="showHtml">
- <textarea v-model="editorHtml" style="width: 100%; height: 400px;"></textarea>
- </div>
- <div v-else>
- <quill-editor ref="quillEditor" v-model="form.detail" :options="editorOptions" class="my-quill-editor"/>
- </div>
- <!-- 多图上传隐藏的input -->
- <input type="file" ref="multiFileInput" @change="handleMultipleFiles" multiple hidden accept="image/jpeg, image/png" />
- </div>
- </el-form-item>
- <el-form-item label="浏览量:" prop="hits" class="custom-align-right">
- <el-input v-model="form.hits" autocomplete="off" placeholder="请输入浏览量"></el-input>
- </el-form-item>
- <el-form-item label="联系人:" prop="contact" class="custom-align-right">
- <el-input v-model="form.contact" autocomplete="off" placeholder="请输入联系人"></el-input>
- </el-form-item>
- <el-form-item label="联系电话:" prop="phone" class="custom-align-right">
- <el-input v-model="form.phone" autocomplete="off" placeholder="请输入联系电话"></el-input>
- </el-form-item>
- <el-form-item label="座机:" prop="landline" class="custom-align-right">
- <el-input v-model="form.landline" autocomplete="off" placeholder="请输入座机"></el-input>
- </el-form-item>
- <el-form-item label="电子邮箱:" prop="email" class="custom-align-right">
- <el-input v-model="form.email" autocomplete="off" placeholder="请输入电子邮件"></el-input>
- </el-form-item>
- <el-form-item label="邮政编码:" prop="postal" class="custom-align-right">
- <el-input v-model="form.postal" autocomplete="off" placeholder="请输入邮政编码"></el-input>
- </el-form-item>
- <el-form-item label="详细地址:" prop="address" class="custom-align-right">
- <el-input v-model="form.address" autocomplete="off" placeholder="请输入详细地址"></el-input>
- </el-form-item>
- </div>
- </el-form>
- </div>
- <div class="bottomBtnBox">
- <el-button type="info" @click="returnPage">返回</el-button>
- <el-button type="primary" @click="editToServe" v-if="editStatus==true">确定</el-button>
- <el-button type="primary" @click="addToServe" v-else>发布商品</el-button>
- </div>
- </div>
- </template>
- <script>
- //表格标题
- import tableTitle from './components/tableTitle';
- //引入公用样式
- import '@/styles/global.less';
- import { quillEditor } from 'vue-quill-editor';
- import 'quill/dist/quill.snow.css';
- import ImageResize from 'quill-image-resize-module';
- import Quill from 'quill'; // 引入 Quill
- import Delta from 'quill-delta'; // 引入 Delta,用于手动修改文档
- //格式化时间
- import { formatLocalDate } from '@/utils/public';
- // 注册 Image Resize 模块
- Quill.register('modules/imageResize', ImageResize);
- //解决富文本样式居中不显示
- import 'quill/dist/quill.core.css';
- export default {
- components: {
- quillEditor,
- tableTitle
- },
- data() {
- //0.全局操作 start ------------------------------------------------------------>
- //表单验证
- const validateEmpty = (rule, value, callback) => {
- console.log(value,'-------------------------------')
- if (value.length == 0) {
- callback(new Error('该项不能为空!'))
- } else {
- callback()
- }
- }
- const validateArray = (rule,value,callback) => {
- if (value.length == 0) {
- callback(new Error('该项不能为空!'))
- } else {
- callback()
- }
- }
- let self = this;
- //0.全局操作 end ------------------------------------------------------------>
- return {
- radio:3,
- checked:false,
- formLabelWidth: '80px',//表单的长度
- //1.表单项 start ------------------------------------------------------------>
- editStatus:false,
- tableDivTitle:"添加商品",
- searchCascaderKey: 0, //列表缓存key
- imgurl:['http://192.168.1.127:9501/image/20250227/1740674706184955.jpg','http://192.168.1.127:9501/image/20250227/1740674706184955.jpg'],//图片路径
- //提交表单
- form: {
- //1.1使用了外链
- name: '',//商品标题
- type_id:1,//布类型:1:供应,2求购
- city_arr_id: [],//行政区划
- city_id: '',//城市id
- cat_arr_id:'',//导航池名称
- website_id: "1",
- catid: "",
- cat_arr_id: "",
- name:"",
- price:"",
- unit:"",
- min:null,
- max:null,
- islong:0,
- validity:"",
- keyword: "",
- description: "",
- detail: "",
- hits: null,
- contact: '',
- phone: '',
- landline: '',
- email: '',
- postal: '',
- address: '',
- city_id :'',
- imgurl:[],//缩略图
- },
- // form: {
- // //1.1使用了外链
- // name: 'ceshi',//商品标题
- // type_id:1,//布类型:1:供应,2求购
- // city_arr_id: [1],//行政区划
- // cat_arr_id:'',//导航池名称
- // website_id: "2",
- // catid: "1",
- // cat_arr_id: [1],
- // name:"商品",
- // price:"100.00",
- // unit:"元",
- // min:"100",
- // max:"1000",
- // islong:"1",
- // validity:"2034-11-08 10:49:47",
- // // imgs: "",
- // keyword: "关键词",
- // description: "描述",
- // detail: "细节",
- // hits: "1",
- // contact: '联系人',
- // phone: '1800000000',
- // landline: '0511-12345678',
- // email: '123456@qq.com',
- // postal: '123456',
- // address: '详细地址',
- // city_id :1,
- // imgurl:['http://192.168.1.127:9501/image/20250227/1740674706184955.jpg','http://192.168.1.127:9501/image/20250227/1740674706184955.jpg'],//缩略图
- // },
- //1.2 表单验证规则
- formRules: {
- type_id:[{required:true,trigger:'blur',validator:validateEmpty}],
- //商品名称不能为空
- name:[{required:true,trigger:'blur',validator:validateEmpty}],
- city_arr_id:[{required:true,trigger:'blur',validator:validateArray}],
- // 导航池名称不能为空
- cat_arr_id: [{ required: true, trigger: 'blur', validator: validateArray }],
- imgurl: [{ required: true, trigger: 'blur', validator: validateArray }],
- price: [{ required: true, trigger: 'blur', validator: validateEmpty }],
- unit: [{ required: true, trigger: 'blur', validator: validateEmpty }],
- validity: [{ required: true, trigger: 'blur', validator: validateEmpty }],
- description: [{ required: true, trigger: 'blur', validator: validateEmpty }],
- keyword: [{ required: true, trigger: 'blur', validator: validateEmpty }],
- contact: [{ required: true, trigger: 'blur', validator: validateEmpty }],
- phone: [{ required: true, trigger: 'blur', validator: validateEmpty }],
- address: [{ required: true, trigger: 'blur', validator: validateEmpty }],
- },
- //1.3富文本编辑器配置
- showHtml: false, //用于保存源码内容
- editorHtml: '',
- cascaderKey: 0,//弹窗用的key
- cityData: {
- checkStrictly: true,
- lazy: true,
- async lazyLoad (node, resolve) {
- const { level, data } = node;
- if (data && data.children && data.children.length !== 0) {
- return resolve(node)
- }
- console.log(level)
- let parentId = level == 0 ? 0 : data.value
- let parames = {
- 'pid':parentId
- }
- self.$store.dispatch('pool/getcityList',parames).then(res=> {
- if (res.data) {
- const nodes = res.data.map(item => ({
- value: item.id,
- label: item.name,
- leaf: level >= 3,
- children: []
- }))
- resolve(nodes)
- }
- })
- }
- },
- editorOptions: {
- placeholder: '请输入内容...',
- theme: 'snow', // 主题样式
- modules: {
- toolbar: {
- container: [
- [{ 'font': [] }], // 字体
- [{ 'header': [1, 2, 3, 4, 5, 6, false] }], // 标题
- [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
- ['bold', 'italic', 'underline', 'strike'], // 加粗、斜体、下划线、删除线
- [{ 'color': [] }, { 'background': [] }], // 文字颜色、背景颜色
- [{ 'script': 'sub' }, { 'script': 'super' }], // 上标、下标
- [{ 'list': 'ordered'}, { 'list': 'bullet' }], // 列表
- [{ 'indent': '-1'}, { 'indent': '+1' }], // 缩进
- [{ 'align': [] }], // 对齐方式
- ['blockquote', 'code-block'], // 引用、代码块
- ['link', 'image', 'video'], // 链接、图片、视频
- ['clean'],
- [{ 'html': true }] // 添加自定义按钮的占位符
- ],
- handlers: {
- image: () => {
- this.handleImageClick();
- },
- showHtml: function() {
- this.$emit('toggleSourceMode');
- }
- }
- },
- imageResize: {
- displayStyles: {
- backgroundColor: 'black',
- border: 'none',
- color: 'white'
- },
- modules: ['Resize', 'DisplaySize', 'Toolbar'] // 启用不同的调整方式
- }
- }
- },
- //1.4图片上传
- imgurl: ['http://192.168.1.127:9501/image/20250227/1740674706184955.jpg', 'http://192.168.1.127:9501/image/20250227/1740674706184955.jpg'],
- imgurl: [],
- //获取父级导航池
- parentKey:0,//获取父级导航
- parentData: {
- checkStrictly: true,
- lazy: true,
- async lazyLoad (node, resolve) {
- const { level, data } = node;
- if (data && data.children && data.children.length !== 0) {
- return resolve(node)
- }
- console.log(level)
- let parentId = level == 0 ? 0 : data.value
- let parames = {
- 'pid':parentId
- }
- self.$store.dispatch('pool/categoryList',parames).then(res=> {
- if (res.data) {
- const nodes = res.data.map(item => ({
- value: item.id,
- label: item.name,
- leaf: level >= 3,
- children: []
- }))
- resolve(nodes)
- }
- })
- }
- },
- inputList: [
- { value: '' }
- ]
- //表单项 end ------------------------------------------------------------>
- };
- },
- methods: {
- //1.提交表单 start ------------------------------------------------------------>
- beforeAvatarUpload(file) {
- const isJPG = file.type === 'image/jpeg';
- const isPNG = file.type === 'image/png';
- const isLt2M = file.size / 1024 / 1024 < 2;
- console.log(this.imgurl.length,'-0--------------------------------')
- if (this.imgurl.length > 4) {
- this.$message.warning('只能上传5张图片');
- return false;
- }
- if (!isJPG && !isPNG) {
- this.$message.error('上传缩略图只能是 JPG 或 PNG 格式!');
- return false;
- }
- if (!isLt2M) {
- this.$message.error('上传缩略图大小不能超过 2MB!');
- return false;
- }
- const formData = new FormData();
- formData.append('file', file);
- this.$store.dispatch('pool/uploadFile',formData).then(res=> {
- this.imgurl.push(res.data.imgUrl);//显示缩略图
- this.form.imgurl.push(res.data.imgUrl);//提供表单地址
- console.log(res.data.imgUrl,'00000')
- })
- // 阻止默认的上传行为
- return false;
- },
- deleteImage(index) { // 删除图片
- this.imgurl.splice(index, 1);
- },
- //1.2 提交表单
- addToServe(){
- //先进行验证
- this.$refs.form.validate(valid => {
- if (valid) {
- if (this.form.validity) {
- console.log(this.form.validity,'p0------------------')
- this.form.validity = formatLocalDate(this.form.validity);
- console.log(this.form.validity,'p1-3333333333333333333333333')
- }
- this.form.imgurl = this.imgurl;
- if(this.form.islong==1){
- this.form.validity = null;
- }
- if(this.form.min==''){
- this.form.min = null;
- }
- if(this.form.max==''){
- this.form.max = null;
- }
- if (this.form.hits == '') {
- this.form.hits = null;
- }
- console.log(this.form,'提交的数据')
- this.$store.dispatch('news/addGood',this.form).then(res=> {
- if(res.code==200){
- //汇报结果
- this.$message({
- type: 'success',
- message: '已成功添加商品!'
- });
- this.cleatForm();
- //返回列表页
- this.returnPage()
- }else{
- this.$message({
- type: 'error',
- message: "商品发布失败,请稍后再试!"
- });
- }
- })
- }
- })
- },
- formatDate(date) {
- if (date instanceof Date) {
- return date.toISOString().slice(0, 19).replace('T', ' ');
- } else if (typeof date === 'string') {
- // 将 ISO 8601 格式的字符串转换为 MySQL 期望的格式
- const parsedDate = new Date(date);
- return parsedDate.toISOString().slice(0, 19).replace('T', ' ');
- } else {
- return date;
- }
- },
- //1.3 清理表单
- cleatForm(){
- },
- //提交表单 end ------------------------------------------------------------>
- //2.跳转操作 start ------------------------------------------------------------>
- returnPage(){
- this.$router.push({
- path: '/goodList',
- });
- },
- //跳转操作 end ------------------------------------------------------------>
- //3.回显操作 ------------------------------------------------------------>
- //3.1回显数据
- getMainData() {
- let data = {
- id: this.$route.query.id
- };
- this.$store.dispatch('news/getGoodInfo', data).then(res => {
- console.log(res);
- this.form.name = res.data.name;
- // 回显导航池
- this.form.cat_arr_id = Array.isArray(res.data.cat_arr_id) ? res.data.cat_arr_id : JSON.parse(res.data.cat_arr_id);
- this.form.city_arr_id = Array.isArray(res.data.city_arr_id) ? res.data.city_arr_id : JSON.parse(res.data.city_arr_id);
- this.parentKey += 1; // 触发级联选择器重新加载
- this.loadCascaderPath(this.form.cat_arr_id); // 加载路径数据
- //回显推荐等级
- this.form.imgurl = Array.isArray(res.data.imgurl) ? res.data.imgurl : JSON.parse(res.data.imgurl);
- this.imgurl = Array.isArray(res.data.imgurl) ? res.data.imgurl : JSON.parse(res.data.imgurl);
- this.form.keyword = res.data.keyword;
- this.form.type_id = res.data.type_id;
- this.form.website_id = res.data.website_id;
- this.form.catid = res.data.catid;
- this.form.price = res.data.price;
- this.form.unit = res.data.unit;
- this.form.min = res.data.min;
- this.form.max = res.data.max;
- this.form.islong = res.data.islong;
- this.form.validity = res.data.validity;
- this.form.keyword = res.data.keyword;
- this.form.description = res.data.description;
- this.form.detail = res.data.detail;
- this.form.hits = res.data.hits;
- this.form.contact = res.data.contact;
- this.form.phone = res.data.phone;
- this.form.landline = res.data.landline;
- this.form.email = res.data.email;
- this.form.postal = res.data.postal;
- this.form.address = res.data.address;
- })
- },
- async loadCascaderPath(path) {
- for (let i = 0; i < path.length; i++) {
- const parentId = path[i - 1] || 0; // 获取当前层级的父级ID
- const level = i; // 当前层级的索引
- await this.$store.dispatch('pool/categoryList', { pid: parentId })
- .then((res) => {
- const nodes = res.data.map(item => ({
- value: item.id,
- label: item.name,
- leaf: level >= 3, // 假设4层结构,设置叶子节点标记
- }));
- // 级联选择器加载数据
- if (level === path.length - 1) {
- this.form.cat_arr_id = path; // 确保最后一级路径正确设置
- this.parentKey += 1; // 强制刷新 cascader
- }
- });
- }
- },
- //1.3提交修改
- editToServe(){
- //提交之前先判断是否为外链
- //如果使用了外链,清理掉除了外链以外的内容
- console.log(this.form)
- //添加要修改的id
- this.form.id = this.editId;
- //先进行验证
- this.$refs.form.validate(valid => {
- if (valid) {
- if (this.form.validity) {
- console.log(this.form.validity,'p0------------------')
- this.form.validity = formatLocalDate(this.form.validity);
- console.log(this.form.validity,'0------------')
- }
- if(this.form.islong==1){
- this.form.validity = null;
- }
- if(this.form.min==''){
- this.form.min = null;
- }
- if(this.form.max==''){
- this.form.max = null;
- }
- if (this.form.hits == '') {
- this.form.hits = null;
- }
- this.form.imgurl = this.imgurl;
- //console.log(this.form)
- this.$store.dispatch('news/updateGood',this.form).then(res=> {
- if(res.code!=200){
- this.$message.error("修改失败,请稍后再试!");
- }else{
- //汇报结果
- this.$message({
- type: 'success',
- message: '已成功编辑商品!'
- });
- this.cleatForm();
- //返回列表页
- this.returnPage()
- }
- }).catch(() => {
- this.$message({
- type: 'info',
- message: '网络错误,请重试!'
- });
- })
- }
- })
- },
- //跳转操作 end ------------------------------------------------------------>
- //4.富文本编辑器 start ------------------------------------------------------------>
- //4.1 编辑器点击上传图片
- handleImageClick() {
- this.$refs.multiFileInput.click(); // 打开文件选择框
- },
- handleMultipleFiles(event) {
- const files = event.target.files;
- if (files.length) {
- this.uploadMultipleImages(files); // 处理多图片上传
- }
- },
- uploadMultipleImages(files) {
- const uploadPromises = [];
- for (let i = 0; i < files.length; i++) {
- uploadPromises.push(this.uploadImage(files[i]));
- }
- Promise.all(uploadPromises).then(urls => {
- const quillEditor = this.$refs.quillEditor.quill;
- urls.forEach(url => {
- const range = quillEditor.getSelection();
- quillEditor.insertEmbed(range.index, 'image', url); // 在编辑器中插入图片
- });
- }).catch(error => {
- this.$message.error('图片上传失败,请重试!');
- });
- },
- uploadImage(file) {
- const formData = new FormData();
- formData.append('file', file);
- return this.$store.dispatch('pool/uploadFile', formData)
- .then(res => {
- if (res && res.data && res.data.imgUrl) {
- return res.data.imgUrl;
- } else {
- throw new Error('图片上传失败');
- }
- })
- .catch(error => {
- this.$message.error('图片上传失败,请重试!');
- throw error;
- });
- },
- //4.2 图片粘贴上传
- // 处理从网页粘贴的图片 URL
- handleImageFromWeb(imageUrl) {
- return new Promise((resolve) => {
- console.log('开始下载图片:', imageUrl);
- this.fetchImageAsBlob(imageUrl).then((blob) => {
- console.log('图片已下载为 Blob:', blob);
- const formData = new FormData();
- formData.append('file', blob, 'image.jpg');
- this.$store.dispatch('pool/uploadFile', formData).then((res) => {
- if (res && res.data && res.data.imgurl) {
- console.log('图片上传成功:', res.data.imgurl);
- resolve(res.data.imgurl);
- } else {
- console.log('图片上传失败,保留原 URL:', imageUrl);
- resolve(imageUrl);
- }
- }).catch((error) => {
- console.error('图片上传时出现错误:', error);
- resolve(imageUrl);
- });
- }).catch((error) => {
- console.error('图片下载失败:', error);
- resolve(imageUrl);
- });
- });
- },
- fetchImageAsBlob(url) {
- return fetch(url)
- .then(response => {
- if (!response.ok) {
- throw new Error('Failed to fetch image');
- }
- return response.blob();
- });
- },
- //编辑源码
- toggleSourceMode() {
- if (!this.showHtml) {
- // 切换到源码模式,将编辑器内容同步到 textarea 中
- this.editorHtml = this.$refs.quillEditor.quill.root.innerHTML;
- this.showHtml = true; // 显示 textarea
- } else {
- // 切换回富文本模式,将 textarea 内容同步回编辑器
- this.showHtml = false; // 显示 Quill 编辑器
- // Quill 编辑器可能被销毁,所以使用 $nextTick 确保 DOM 渲染完成后再操作编辑器
- this.$nextTick(() => {
- if (this.$refs.quillEditor) {
- this.$refs.quillEditor.quill.root.innerHTML = this.editorHtml;
- } else {
- console.error('Quill 编辑器实例未找到');
- }
- });
- }
- }
- //富文本编辑器 end ------------------------------------------------------------>
- },
- watch: {
- 'form.type_id': {
- handler(newVal, oldVal) {
- if (newVal !== oldVal) {
- console.log('---------变化了------------');
- this.form.name = '';
- this.form.city_arr_id = [];
- this.form.city_id = '';
- this.form.cat_arr_id = '';
- this.form.website_id = "1";
- this.form.catid = "";
- this.form.price = "";
- this.form.unit = "";
- this.form.min = null;
- this.form.max = null;
- this.form.islong = 0;
- this.form.validity = "";
- this.form.keyword = "";
- this.form.description = "";
- this.form.detail = "";
- this.form.hits = null;
- this.form.contact = '';
- this.form.phone = '';
- this.form.landline = '';
- this.form.email = '';
- this.form.postal = '';
- this.form.address = '';
- this.form.imgurl = [];
- this.form.city_id = '';
- // 清空特定字段的数据
- if (newVal === 1) {
- // 从求购商品切换到供应商品
- this.form.price = '';
- console.log('供应商品');
- } else if (newVal === 2) {
- // 从供应商品切换到求购商品
- console.log('求购商品');
- }
- }
- },
- immediate: true // 立即执行一次
- }
- },
- mounted(){
- //1.判断是新建还是回显
- if(this.$route.query.id!=undefined){
- this.editId = this.$route.query.id;
- this.editStatus = true;
- this.tableDivTitle = "编辑商品";
- console.log("编辑商品")
- this.getMainData();
- }else{
- this.editStatus = false;
- console.log("添加商品!")
- }
- //复制内容到富文本 start ------------------------------------------------------------>
- this.$nextTick(() => {
- const quillEditor = this.$refs.quillEditor.quill;
- if (quillEditor) {
- console.log('Quill 编辑器已初始化');
- // 在粘贴事件触发时,记录所有 img 的 src
- quillEditor.clipboard.addMatcher(Node.ELEMENT_NODE, (node, delta) => {
- if (node.tagName === 'IMG') {
- const imageUrl = node.getAttribute('src');
- console.log('检测到粘贴的图片 URL:', imageUrl);
- if (imageUrl && !imageUrl.startsWith('data:') && !imageUrl.startsWith('file://')) {
- // 先处理图片上传
- this.handleImageFromWeb(imageUrl).then((uploadedImageUrl) => {
- // 查找编辑器中所有 img 标签并替换 src
- const imgs = quillEditor.root.querySelectorAll('img');
- imgs.forEach((img) => {
- if (img.getAttribute('src') === imageUrl) {
- img.setAttribute('src', uploadedImageUrl); // 替换 src
- console.log('图片 src 已替换为:', uploadedImageUrl);
- }
- });
- });
- }
- }
- return delta; // 返回原始 delta
- });
- } else {
- console.error('Quill 初始化失败');
- }
- });
- //复制富文本 end ------------------------------------------------------------>
- },
- };
- </script>
- <style scoped lang="less">
- //文本编辑器
- .QuillTitle {
- line-height: 36px;
- font-size: 14px;
- color: #606266;
- font-weight:bold;
- padding-left: 30px;
- span{
- color: #ff4949
- }
- .QuillModelBtn {
- display: inline-block;
- margin-left: 10px;
- font-size: 12px;
- color: #999;
- cursor: pointer;
- }
- }
- .editor-container {
- height: 420px;
- padding-bottom:20px;
- }
- .my-quill-editor {
- height: 320px;
- }
- .ql-editor {
- height: 320px;
- }
- /* 富文本对齐方式 */
- .ql-align-center{
- text-align: center;
- }
- .ql-align-right{
- text-align: right;
- }
- .ql-indent-1{
- padding-left: 16px;
- }
- .ql-indent-2{
- padding-left: 32px;
- }
- .ql-indent-3{
- padding-left: 48px;
- }
- .ql-indent-4{
- padding-left: 64px;
- }
- .ql-indent-5{
- padding-left: 80px;
- }
- .ql-indent-6{
- padding-left: 96px;
- }
- .ql-indent-7{
- padding-left: 112px;
- }
- .ql-indent-8{
- padding-left: 128px;
- }
- //执行v-deep穿透scope选择器 start------------------------------------------------------------>*/
- ::v-deep .custom-form-item > .el-form-item__label {
- line-height: 140px !important;
- }
- ::v-deep .custom-textarea .el-textarea__inner {
- resize: none; /* 禁止用户拖拽调整大小 */
- }
- ::v-deep .custom-align-right .el-form-item__label {
- text-align: right; /* 设置标签文字右对齐 */
- }
- ::v-deep .el-select {
- width: 100%; /* 禁止用户拖拽调整大小 */
- }
- ::v-deep .el-input-group__prepend {
- color: black !important;
- }
- .formLabelFloatBox {
- margin-bottom: 10px;
- position: relative;
- .formLabeladdIcon {
- position: absolute;
- right:45px;
- top:5px;
- width:38px;
- height:24px;
- }
- .formLabelDelIcon {
- position: absolute;
- right:5px;
- top:5px;
- width:38px;
- height:24px;
- }
- }
- //执行v-deep穿透scope选择器 end------------------------------------------------------------>*/
- </style>
|