addGood.vue 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. <template>
  2. <div class="mainBox">
  3. <div class="layerBox">
  4. <tableTitle :name="tableDivTitle" />
  5. <el-form :model="form" ref="form" :rules="formRules" label-position="left" label-width="120px">
  6. <div class="formDiv">
  7. <el-form-item label="发布类型" prop="type_id" class="custom-align-right">
  8. <el-radio-group v-model="form.type_id">
  9. <el-radio :label="1">供应商品</el-radio>
  10. <el-radio :label="2">求购商品</el-radio>
  11. </el-radio-group>
  12. </el-form-item>
  13. <el-form-item label="商品名称:" prop="name" class="custom-align-right">
  14. <template #label>
  15. <span class="askBox" v-if="form.type_id == 1">
  16. 商品名称:
  17. </span>
  18. <span class="askBox" v-if="form.type_id == 2">
  19. 标题:
  20. </span>
  21. </template>
  22. <el-input v-model="form.name" autocomplete="off" placeholder="请输入商品标题"></el-input>
  23. </el-form-item>
  24. <el-form-item label="发布地点:" prop="city_arr_id" class="custom-align-right">
  25. <el-cascader :key="cascaderKey" v-model="form.city_arr_id" placeholder="发布地区:" :props="cityData" filterable
  26. clearable></el-cascader>
  27. </el-form-item>
  28. <el-form-item label="网站:" prop="website_id" class="custom-align-right" v-if="userType != 10000">
  29. <el-select v-model="form.website_id" placeholder="请选择网站" filterable clearable>
  30. <el-option v-for="item in websiteOptions" :key="item.value" :label="item.label" :value="item.value">
  31. </el-option>
  32. </el-select>
  33. </el-form-item>
  34. <el-form-item label="导航池名称:" prop="cat_arr_id" class="custom-align-right">
  35. <el-cascader :key="parentKey" v-model="form.cat_arr_id" placeholder="请选择要绑定的导航池名称" :props="parentData"
  36. filterable clearable></el-cascader>
  37. </el-form-item>
  38. <div v-if="form.type_id == 1">
  39. <el-form-item label="商品单价:" prop="price" class="custom-align-right">
  40. <el-input type="number" v-model="form.price" autocomplete="off" placeholder="请输入商品单价">
  41. <template #suffix>
  42. </template>
  43. </el-input>
  44. </el-form-item>
  45. <el-form-item label="单位:" prop="unit" class="custom-align-right">
  46. <el-input v-model="form.unit" autocomplete="off" placeholder="请输入单位"></el-input>
  47. </el-form-item>
  48. <el-form-item label="最小定量:" prop="min" class="custom-align-right">
  49. <el-input v-model="form.min" autocomplete="off" placeholder="请输入最小定量"></el-input>
  50. </el-form-item>
  51. <el-form-item label="供货总量:" prop="max" class="custom-align-right">
  52. <el-input v-model="form.max" autocomplete="off" placeholder="请输入供货总量"></el-input>
  53. </el-form-item>
  54. <el-form-item label="有效期:" prop="validity" class="custom-align-right">
  55. <el-date-picker v-model="form.validity" type="date" placeholder="选择日期" :disabled="form.islong == 1">
  56. </el-date-picker>
  57. <el-checkbox v-model="form.islong">无期限</el-checkbox>
  58. </el-form-item>
  59. </div>
  60. <div v-if="form.type_id == 2">
  61. <el-form-item label="截止日期:" prop="validity" class="custom-align-right">
  62. <el-date-picker v-model="form.validity" type="date" placeholder="选择日期" :disabled="form.islong == 1">
  63. </el-date-picker>
  64. <el-checkbox v-model="form.islong">无期限</el-checkbox>
  65. </el-form-item>
  66. </div>
  67. <el-form-item label="商品图:" class="custom-align-right" prop="imgurl">
  68. <div class="uploaderBox">
  69. <span v-if="imgurl.length > 0" class="uploaded-images">
  70. <div v-for="(url, index) in imgurl" :key="index" style="display: inline;float: left; width: 150px;;">
  71. <img :src="url" class="avatar" style="float: left; margin-right: 10px;">
  72. <div style="position: relative;
  73. transform: translate(-50%, -50%);
  74. right: -120px;
  75. top: -20px;
  76. background-color: rgba(0, 0, 0, 0.5);
  77. color: white;
  78. border-radius: 50%;
  79. width: 24px;
  80. height: 24px;
  81. display: flex;
  82. align-items: center;
  83. justify-content: center;
  84. cursor: pointer;
  85. z-index: 10;" @click="deleteImage(index)">
  86. <i class="el-icon-delete"></i>
  87. </div>
  88. </div>
  89. </span>
  90. <el-upload class="avatar-uploader1" action="#" :show-file-list="true" :before-upload="beforeAvatarUpload"
  91. style="display: inline;">
  92. <div style="width: 100px; display: inline-block;">
  93. <img src="@/assets/public/upload/noImage.png">
  94. <div>选择图片</div>
  95. </div>
  96. </el-upload>
  97. </div>
  98. </el-form-item>
  99. <div class="imgBox" style="margin-left: 100px ;margin-bottom: 20px; padding-top: -20px;">
  100. 最多可上传5张,每张图片大小不能超过500K,推荐上传图片尺寸
  101. 宽1000像素 高1000像素。(首张显示为商品头图)</div>
  102. <el-form-item label="商品关键词:" prop="keyword" class="custom-align-right">
  103. <el-input v-model="form.keyword" autocomplete="off" placeholder="请输入商品关键词"></el-input>
  104. </el-form-item>
  105. <el-form-item label="商品描述:" prop="description" class="custom-align-right">
  106. <el-input v-model="form.description" maxlength="300" autocomplete="off" placeholder="请输入商品描述"
  107. type="textarea" :rows="10"></el-input>
  108. </el-form-item>
  109. <div class="QuillTitle">
  110. <span>* </span> <span style="color: #606266" v-if="form.type_id == 1">商品详情:</span><span
  111. style="color: #606266" v-else>详情说明:</span>
  112. <div @click="toggleSourceMode" class="QuillModelBtn">
  113. {{ showHtml ? '切换到编辑模式' : '切换到源码模式' }}
  114. </div>
  115. </div>
  116. <el-form-item label="" prop="detail">
  117. <div class="editor-container">
  118. <div v-if="showHtml">
  119. <textarea v-model="editorHtml" style="width: 100%; height: 400px;"></textarea>
  120. </div>
  121. <div v-else>
  122. <quill-editor ref="quillEditor" v-model="form.detail" :options="editorOptions"
  123. class="my-quill-editor" />
  124. </div>
  125. <!-- 多图上传隐藏的input -->
  126. <input type="file" ref="multiFileInput" @change="handleMultipleFiles" multiple hidden
  127. accept="image/jpeg, image/png" />
  128. </div>
  129. </el-form-item>
  130. <el-form-item label="浏览量:" prop="hits" class="custom-align-right">
  131. <el-input type="number" v-model="form.hits" autocomplete="off" placeholder="请输入浏览量"></el-input>
  132. </el-form-item>
  133. <el-form-item label="联系人:" prop="contact" class="custom-align-right">
  134. <el-input v-model="form.contact" autocomplete="off" placeholder="请输入联系人"></el-input>
  135. </el-form-item>
  136. <el-form-item label="联系电话:" prop="phone" class="custom-align-right">
  137. <el-input v-model="form.phone" autocomplete="off" placeholder="请输入联系电话"></el-input>
  138. </el-form-item>
  139. <el-form-item label="座机:" prop="landline" class="custom-align-right">
  140. <el-input v-model="form.landline" autocomplete="off" placeholder="请输入座机"></el-input>
  141. </el-form-item>
  142. <el-form-item label="电子邮箱:" prop="email" class="custom-align-right">
  143. <el-input type="email" v-model="form.email" autocomplete="off" placeholder="请输入电子邮件"></el-input>
  144. </el-form-item>
  145. <el-form-item label="邮政编码:" prop="postal" class="custom-align-right">
  146. <el-input type="number" v-model="form.postal" autocomplete="off" placeholder="请输入邮政编码"></el-input>
  147. </el-form-item>
  148. <el-form-item label="详细地址:" prop="address" class="custom-align-right">
  149. <el-input v-model="form.address" autocomplete="off" placeholder="请输入详细地址"></el-input>
  150. </el-form-item>
  151. </div>
  152. </el-form>
  153. </div>
  154. <div class="bottomBtnBox">
  155. <el-button type="info" @click="returnPage">返回</el-button>
  156. <el-button type="primary" @click="editToServe" v-if="editStatus == true">确定</el-button>
  157. <el-button type="primary" @click="addToServe" v-else>发布商品</el-button>
  158. </div>
  159. </div>
  160. </template>
  161. <script>
  162. //表格标题
  163. import tableTitle from './components/tableTitle';
  164. //引入公用样式
  165. import '@/styles/global.less';
  166. import { quillEditor } from 'vue-quill-editor';
  167. import 'quill/dist/quill.snow.css';
  168. import ImageResize from 'quill-image-resize-module';
  169. import Quill from 'quill'; // 引入 Quill
  170. import Delta from 'quill-delta'; // 引入 Delta,用于手动修改文档
  171. //格式化时间
  172. import { formatLocalDate } from '@/utils/public';
  173. // 注册 Image Resize 模块
  174. Quill.register('modules/imageResize', ImageResize);
  175. //解决富文本样式居中不显示
  176. import 'quill/dist/quill.core.css';
  177. export default {
  178. components: {
  179. quillEditor,
  180. tableTitle
  181. },
  182. data() {
  183. //0.全局操作 start ------------------------------------------------------------>
  184. //表单验证
  185. const validateNull = (rule, value, callback) => {
  186. console.log(value, '-------------------------------')
  187. if (value == '' || value == undefined || value == null) {
  188. callback(new Error('该项不能为空!'))
  189. } else {
  190. callback()
  191. }
  192. }
  193. const validateEmpty = (rule, value, callback) => {
  194. console.log(value, '-------------------------------')
  195. if (value.length == 0) {
  196. callback(new Error('该项不能为空!'))
  197. } else {
  198. callback()
  199. }
  200. }
  201. const validateArray = (rule, value, callback) => {
  202. if (value.length == 0) {
  203. callback(new Error('该项不能为空!'))
  204. } else {
  205. callback()
  206. }
  207. }
  208. let self = this;
  209. //0.全局操作 end ------------------------------------------------------------>
  210. return {
  211. userType: 0,
  212. websiteOptions: [],
  213. checked: false,
  214. formLabelWidth: '80px',//表单的长度
  215. //1.表单项 start ------------------------------------------------------------>
  216. editStatus: false,
  217. tableDivTitle: "添加商品",
  218. searchCascaderKey: 0, //列表缓存key
  219. // imgurl: ['http://192.168.1.127:9501/image/20250227/1740674706184955.jpg', 'http://192.168.1.127:9501/image/20250227/1740674706184955.jpg'],//图片路径
  220. website_id: 2,
  221. //提交表单
  222. form: {
  223. //1.1使用了外链
  224. name: '',//商品标题
  225. type_id: 1,//布类型:1:供应,2求购
  226. city_arr_id: [],//行政区划
  227. city_id: '',//城市id
  228. cat_arr_id: '',//导航池名称
  229. website_id: 2,
  230. catid: "",
  231. cat_arr_id: "",
  232. name: "",
  233. price: "",
  234. unit: "",
  235. min: null,
  236. max: null,
  237. islong: 0,
  238. validity: "",
  239. keyword: "",
  240. description: "",
  241. detail: "",
  242. hits: null,
  243. contact: '',
  244. phone: '',
  245. landline: '',
  246. email: '',
  247. postal: '',
  248. address: '',
  249. city_id: '',
  250. imgurl: [],//缩略图
  251. },
  252. // form: {
  253. // //1.1使用了外链
  254. // name: 'ceshi',//商品标题
  255. // type_id:1,//布类型:1:供应,2求购
  256. // city_arr_id: [1],//行政区划
  257. // cat_arr_id:'',//导航池名称
  258. // website_id: "2",
  259. // catid: "1",
  260. // cat_arr_id: [1],
  261. // name:"商品",
  262. // price:"100.00",
  263. // unit:"元",
  264. // min:"100",
  265. // max:"1000",
  266. // islong:"1",
  267. // validity:"2034-11-08 10:49:47",
  268. // // imgs: "",
  269. // keyword: "关键词",
  270. // description: "描述",
  271. // detail: "细节",
  272. // hits: "1",
  273. // contact: '联系人',
  274. // phone: '1800000000',
  275. // landline: '0511-12345678',
  276. // email: '123456@qq.com',
  277. // postal: '123456',
  278. // address: '详细地址',
  279. // city_id :1,
  280. // imgurl:['http://192.168.1.127:9501/image/20250227/1740674706184955.jpg','http://192.168.1.127:9501/image/20250227/1740674706184955.jpg'],//缩略图
  281. // },
  282. //1.2 表单验证规则
  283. formRules: {
  284. type_id: [{ required: true, trigger: 'blur', validator: validateEmpty }],
  285. //商品名称不能为空
  286. name: [{ required: true, trigger: 'blur', validator: validateEmpty }],
  287. city_arr_id: [{ required: true, trigger: 'blur', validator: validateArray }],
  288. // 导航池名称不能为空
  289. cat_arr_id: [{ required: true, trigger: 'blur', validator: validateArray }],
  290. imgurl: [{ required: true, trigger: 'blur', validator: validateArray }],
  291. website_id: [{ required: true, trigger: 'blur', validator: validateEmpty }],
  292. price: [{ required: true, trigger: 'blur', validator: validateEmpty }],
  293. unit: [{ required: true, trigger: 'blur', validator: validateEmpty }],
  294. validity: [{ required: true, trigger: 'blur', validator: validateNull }],
  295. description: [{ required: true, trigger: 'blur', validator: validateEmpty }],
  296. keyword: [{ required: true, trigger: 'blur', validator: validateEmpty }],
  297. contact: [{ required: true, trigger: 'blur', validator: validateEmpty }],
  298. phone: [{ required: true, trigger: 'blur', validator: validateEmpty }],
  299. address: [{ required: true, trigger: 'blur', validator: validateEmpty }],
  300. },
  301. //1.3富文本编辑器配置
  302. showHtml: false, //用于保存源码内容
  303. editorHtml: '',
  304. cascaderKey: 0,//弹窗用的key
  305. websiteData: {
  306. lazy: true,
  307. checkStrictly: true,
  308. async lazyLoad(node, resolve) {
  309. const { level, data } = node;
  310. if (data && data.children && data.children.length !== 0) {
  311. return resolve(node)
  312. }
  313. console.log(level)
  314. let parentId = level == 0 ? 0 : data.value
  315. let parames = {
  316. 'page': 1,
  317. 'pageSize': 1000,
  318. }
  319. self.$store.dispatch('news/websiteList', parames).then(res => {
  320. if (res.data) {
  321. const nodes = res.data.rows.map(item => ({
  322. value: item.id,
  323. label: item.website_name,
  324. leaf: level >= 3,
  325. children: []
  326. }))
  327. console.log(nodes, 'leaf')
  328. resolve(nodes)
  329. }
  330. })
  331. },
  332. },
  333. cityData: {
  334. checkStrictly: true,
  335. lazy: true,
  336. async lazyLoad(node, resolve) {
  337. const { level, data } = node;
  338. if (data && data.children && data.children.length !== 0) {
  339. return resolve(node)
  340. }
  341. console.log(level, '====level-----')
  342. let parentId = level == 0 ? 0 : data.value
  343. let parames = {
  344. 'pid': parentId
  345. }
  346. self.$store.dispatch('pool/getcityList', parames).then(res => {
  347. if (res.data) {
  348. const nodes = res.data.map(item => ({
  349. value: item.id,
  350. label: item.name,
  351. leaf: level >= 3,
  352. children: []
  353. }))
  354. resolve(nodes)
  355. }
  356. })
  357. }
  358. },
  359. editorOptions: {
  360. placeholder: '请输入内容...',
  361. theme: 'snow', // 主题样式
  362. modules: {
  363. toolbar: {
  364. container: [
  365. [{ 'font': [] }], // 字体
  366. [{ 'header': [1, 2, 3, 4, 5, 6, false] }], // 标题
  367. [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
  368. ['bold', 'italic', 'underline', 'strike'], // 加粗、斜体、下划线、删除线
  369. [{ 'color': [] }, { 'background': [] }], // 文字颜色、背景颜色
  370. [{ 'script': 'sub' }, { 'script': 'super' }], // 上标、下标
  371. [{ 'list': 'ordered' }, { 'list': 'bullet' }], // 列表
  372. [{ 'indent': '-1' }, { 'indent': '+1' }], // 缩进
  373. [{ 'align': [] }], // 对齐方式
  374. ['blockquote', 'code-block'], // 引用、代码块
  375. ['link', 'image', 'video'], // 链接、图片、视频
  376. ['clean'],
  377. [{ 'html': true }] // 添加自定义按钮的占位符
  378. ],
  379. handlers: {
  380. image: () => {
  381. this.handleImageClick();
  382. },
  383. showHtml: function () {
  384. this.$emit('toggleSourceMode');
  385. }
  386. }
  387. },
  388. imageResize: {
  389. displayStyles: {
  390. backgroundColor: 'black',
  391. border: 'none',
  392. color: 'white'
  393. },
  394. modules: ['Resize', 'DisplaySize', 'Toolbar'] // 启用不同的调整方式
  395. }
  396. }
  397. },
  398. //1.4图片上传
  399. // imgurl: ['http://192.168.1.127:9501/image/20250227/1740674706184955.jpg', 'http://192.168.1.127:9501/image/20250227/1740674706184955.jpg'],
  400. imgurl: [],
  401. //获取父级导航池
  402. parentKey: 0,//获取父级导航
  403. parentData: {
  404. checkStrictly: true,
  405. lazy: true,
  406. async lazyLoad(node, resolve) {
  407. console.log(resolve, 'node')
  408. const { level, data } = node;
  409. if (data && data.children && data.children.length !== 0) {
  410. return resolve(node)
  411. }
  412. console.log(level, 'level--1--');
  413. let pid = level == 0 ? 0 : data.value
  414. let website_id = self.form.website_id == '' ? 2 : self.form.website_id;
  415. console.log(website_id, 'website_id--111-----');
  416. let parames = {
  417. 'website_id': website_id,
  418. 'pid': pid
  419. }
  420. self.$store.dispatch('news/getWebsiteNavList', parames).then(res => {
  421. if (res.data) {
  422. const nodes = res.data.map(item => ({
  423. value: item.category_id,
  424. label: item.name,
  425. leaf: level >= 3,
  426. children: []
  427. }))
  428. resolve(nodes)
  429. } else {
  430. //输出报错原因
  431. console.log(res.msg, 'getWebsiteNavList--1--');
  432. }
  433. })
  434. }
  435. },
  436. inputList: [
  437. { value: '' }
  438. ]
  439. //表单项 end ------------------------------------------------------------>
  440. };
  441. },
  442. methods: {
  443. async fetchWebsiteOptions() {
  444. try {
  445. const response = await this.$store.dispatch('news/websiteList', { page: 1, pageSize: 1000 });
  446. if (response && response.data) {
  447. this.websiteOptions = response.data.rows.map(item => ({
  448. value: item.id,
  449. label: item.website_name,
  450. }));
  451. }
  452. } catch (error) {
  453. console.error('获取网站列表失败:', error);
  454. }
  455. },
  456. //获取用户身份信息
  457. getUserInfo() {
  458. this.$store.dispatch('public/getInfo').then(res => {
  459. console.log(res)
  460. this.userType = res.data.type_id;
  461. if (this.userType == 10000) {
  462. this.form.website_id = res.data.website_id !== undefined ? res.data.website_id : 2;;
  463. }
  464. //if(res.data.type_id==10000){}//管理员
  465. //if(res.data.type_id==4){}//调研员
  466. //个人会员=1 政务会员=2 企业会员=3 调研员=4 管理员=10000 游客=20000
  467. }).catch(() => {
  468. this.$message({
  469. type: 'info',
  470. message: '网络错误,请重试!'
  471. });
  472. })
  473. },
  474. //1.提交表单 start ------------------------------------------------------------>
  475. beforeAvatarUpload(file) {
  476. const isJPG = file.type === 'image/jpeg';
  477. const isPNG = file.type === 'image/png';
  478. const isLt2M = file.size / 1024 / 1024 < 2;
  479. console.log(this.imgurl.length, '-0--------------------------------')
  480. if (this.imgurl.length > 4) {
  481. this.$message.warning('只能上传5张图片');
  482. return false;
  483. }
  484. if (!isJPG && !isPNG) {
  485. this.$message.error('上传缩略图只能是 JPG 或 PNG 格式!');
  486. return false;
  487. }
  488. if (!isLt2M) {
  489. this.$message.error('上传缩略图大小不能超过 2MB!');
  490. return false;
  491. }
  492. const formData = new FormData();
  493. formData.append('file', file);
  494. this.$store.dispatch('pool/uploadFile', formData).then(res => {
  495. this.imgurl.push(res.data.imgUrl);//显示缩略图
  496. this.form.imgurl.push(res.data.imgUrl);//提供表单地址
  497. console.log(res.data.imgUrl, '00000')
  498. })
  499. // 阻止默认的上传行为
  500. return false;
  501. },
  502. deleteImage(index) { // 删除图片
  503. this.imgurl.splice(index, 1);
  504. },
  505. //1.2 提交表单
  506. addToServe() {
  507. //先进行验证
  508. this.$refs.form.validate(valid => {
  509. if (this.form.islong == 1 && this.form.validity == null) {
  510. this.form.validity = '1970-01-01 00:00:00';
  511. }
  512. if (valid) {
  513. if (this.form.validity) {
  514. console.log(this.form.validity, 'p0------------------')
  515. this.form.validity = formatLocalDate(this.form.validity);
  516. console.log(this.form.validity, 'p1-3333333333333333333333333')
  517. }
  518. this.form.imgurl = this.imgurl;
  519. if (this.form.islong == 1) {
  520. this.form.validity = null;
  521. }
  522. if (this.form.min == '') {
  523. this.form.min = null;
  524. }
  525. if (this.form.max == '') {
  526. this.form.max = null;
  527. }
  528. if (this.form.hits == '') {
  529. this.form.hits = null;
  530. }
  531. console.log(this.form, '提交的数据')
  532. this.$store.dispatch('news/addGood', this.form).then(res => {
  533. if (res.code == 200) {
  534. //汇报结果
  535. this.$message({
  536. type: 'success',
  537. message: '已成功添加商品!'
  538. });
  539. this.cleatForm();
  540. //返回列表页
  541. this.returnPage()
  542. } else {
  543. this.$message({
  544. type: 'error',
  545. message: "商品发布失败,请稍后再试!"
  546. });
  547. }
  548. })
  549. }
  550. })
  551. },
  552. formatDate(date) {
  553. if (date instanceof Date) {
  554. return date.toISOString().slice(0, 19).replace('T', ' ');
  555. } else if (typeof date === 'string') {
  556. // 将 ISO 8601 格式的字符串转换为 MySQL 期望的格式
  557. const parsedDate = new Date(date);
  558. return parsedDate.toISOString().slice(0, 19).replace('T', ' ');
  559. } else {
  560. return date;
  561. }
  562. },
  563. //1.3 清理表单
  564. cleatForm() {
  565. },
  566. //提交表单 end ------------------------------------------------------------>
  567. //2.跳转操作 start ------------------------------------------------------------>
  568. returnPage() {
  569. this.$router.push({
  570. path: '/goodList',
  571. });
  572. },
  573. //跳转操作 end ------------------------------------------------------------>
  574. //3.回显操作 ------------------------------------------------------------>
  575. //3.1回显数据
  576. getMainData() {
  577. let data = {
  578. id: this.$route.query.id
  579. };
  580. this.$store.dispatch('news/getGoodInfo', data).then(res => {
  581. console.log(res);
  582. this.form.name = res.data.name;
  583. // 回显导航池
  584. this.form.cat_arr_id = Array.isArray(res.data.cat_arr_id) ? res.data.cat_arr_id : JSON.parse(res.data.cat_arr_id);
  585. this.form.city_arr_id = Array.isArray(res.data.city_arr_id) ? res.data.city_arr_id : JSON.parse(res.data.city_arr_id);
  586. this.parentKey += 1; // 触发级联选择器重新加载
  587. this.loadCascaderPath(this.form.cat_arr_id); // 加载路径数据
  588. //回显推荐等级
  589. this.form.imgurl = Array.isArray(res.data.imgurl) ? res.data.imgurl : JSON.parse(res.data.imgurl);
  590. this.imgurl = Array.isArray(res.data.imgurl) ? res.data.imgurl : JSON.parse(res.data.imgurl);
  591. this.form.keyword = res.data.keyword;
  592. this.form.type_id = res.data.type_id;
  593. this.form.website_id = res.data.website_id;
  594. this.form.catid = res.data.catid;
  595. this.form.price = res.data.price;
  596. this.form.unit = res.data.unit;
  597. this.form.min = res.data.min;
  598. this.form.max = res.data.max;
  599. this.form.islong = res.data.islong == 1 ? true : false;
  600. this.form.validity = res.data.validity;
  601. this.form.keyword = res.data.keyword;
  602. this.form.description = res.data.description;
  603. this.form.detail = res.data.detail;
  604. this.form.hits = res.data.hits;
  605. this.form.contact = res.data.contact;
  606. this.form.phone = res.data.phone;
  607. this.form.landline = res.data.landline;
  608. this.form.email = res.data.email;
  609. this.form.postal = res.data.postal;
  610. this.form.address = res.data.address;
  611. })
  612. },
  613. async loadCascaderPath(path) {
  614. for (let i = 0; i < path.length; i++) {
  615. const parentId = path[i - 1] || 0; // 获取当前层级的父级ID
  616. const level = i; // 当前层级的索引
  617. // self.$store.dispatch('news/getWebsiteNavList', parames).then(res => {
  618. // if (res.data) {
  619. // const nodes = res.data.map(item => ({
  620. // value: item.category_id,
  621. // label: item.name,
  622. // leaf: level >= 3,
  623. // children: []
  624. // }))
  625. // resolve(nodes)
  626. await this.$store.dispatch('pool/categoryList', { pid: parentId })
  627. .then((res) => {
  628. const nodes = res.data.map(item => ({
  629. value: item.id,
  630. label: item.name,
  631. leaf: level >= 3, // 假设4层结构,设置叶子节点标记
  632. }));
  633. // 级联选择器加载数据
  634. if (level === path.length - 1) {
  635. this.form.cat_arr_id = path; // 确保最后一级路径正确设置
  636. this.parentKey += 1; // 强制刷新 cascader
  637. }
  638. });
  639. }
  640. },
  641. //1.3提交修改
  642. editToServe() {
  643. //提交之前先判断是否为外链
  644. //如果使用了外链,清理掉除了外链以外的内容
  645. console.log(this.form)
  646. //添加要修改的id
  647. this.form.id = this.editId;
  648. //先进行验证
  649. console.log(this.form.validity, 'validity')
  650. if (this.form.islong == 1 && this.form.validity == null) {
  651. this.form.validity = '1970-01-01 00:00:00';
  652. }
  653. this.$refs.form.validate(valid => {
  654. if (valid) {
  655. if (this.form.validity) {
  656. console.log(this.form.validity, 'p0------------------')
  657. this.form.validity = formatLocalDate(this.form.validity);
  658. console.log(this.form.validity, '0------------')
  659. }
  660. if (this.form.islong == 1) {
  661. this.form.validity = null;
  662. }
  663. if (this.form.min == '') {
  664. this.form.min = null;
  665. }
  666. if (this.form.max == '') {
  667. this.form.max = null;
  668. }
  669. if (this.form.hits == '') {
  670. this.form.hits = null;
  671. }
  672. this.form.imgurl = this.imgurl;
  673. //console.log(this.form)
  674. this.$store.dispatch('news/updateGood', this.form).then(res => {
  675. if (res.code != 200) {
  676. this.$message.error("修改失败,请稍后再试!");
  677. } else {
  678. //汇报结果
  679. this.$message({
  680. type: 'success',
  681. message: '已成功编辑商品!'
  682. });
  683. this.cleatForm();
  684. //返回列表页
  685. this.returnPage()
  686. }
  687. }).catch(() => {
  688. this.$message({
  689. type: 'info',
  690. message: '网络错误,请重试!'
  691. });
  692. })
  693. }
  694. })
  695. },
  696. //跳转操作 end ------------------------------------------------------------>
  697. //4.富文本编辑器 start ------------------------------------------------------------>
  698. //4.1 编辑器点击上传图片
  699. handleImageClick() {
  700. this.$refs.multiFileInput.click(); // 打开文件选择框
  701. },
  702. handleMultipleFiles(event) {
  703. const files = event.target.files;
  704. if (files.length) {
  705. this.uploadMultipleImages(files); // 处理多图片上传
  706. }
  707. },
  708. uploadMultipleImages(files) {
  709. const uploadPromises = [];
  710. for (let i = 0; i < files.length; i++) {
  711. uploadPromises.push(this.uploadImage(files[i]));
  712. }
  713. Promise.all(uploadPromises).then(urls => {
  714. const quillEditor = this.$refs.quillEditor.quill;
  715. urls.forEach(url => {
  716. const range = quillEditor.getSelection();
  717. quillEditor.insertEmbed(range.index, 'image', url); // 在编辑器中插入图片
  718. });
  719. }).catch(error => {
  720. this.$message.error('图片上传失败,请重试!');
  721. });
  722. },
  723. uploadImage(file) {
  724. const formData = new FormData();
  725. formData.append('file', file);
  726. return this.$store.dispatch('pool/uploadFile', formData)
  727. .then(res => {
  728. if (res && res.data && res.data.imgUrl) {
  729. return res.data.imgUrl;
  730. } else {
  731. throw new Error('图片上传失败');
  732. }
  733. })
  734. .catch(error => {
  735. this.$message.error('图片上传失败,请重试!');
  736. throw error;
  737. });
  738. },
  739. //4.2 图片粘贴上传
  740. // 处理从网页粘贴的图片 URL
  741. handleImageFromWeb(imageUrl) {
  742. return new Promise((resolve) => {
  743. console.log('开始下载图片:', imageUrl);
  744. this.fetchImageAsBlob(imageUrl).then((blob) => {
  745. console.log('图片已下载为 Blob:', blob);
  746. const formData = new FormData();
  747. formData.append('file', blob, 'image.jpg');
  748. this.$store.dispatch('pool/uploadFile', formData).then((res) => {
  749. if (res && res.data && res.data.imgurl) {
  750. console.log('图片上传成功:', res.data.imgurl);
  751. resolve(res.data.imgurl);
  752. } else {
  753. console.log('图片上传失败,保留原 URL:', imageUrl);
  754. resolve(imageUrl);
  755. }
  756. }).catch((error) => {
  757. console.error('图片上传时出现错误:', error);
  758. resolve(imageUrl);
  759. });
  760. }).catch((error) => {
  761. console.error('图片下载失败:', error);
  762. resolve(imageUrl);
  763. });
  764. });
  765. },
  766. fetchImageAsBlob(url) {
  767. return fetch(url)
  768. .then(response => {
  769. if (!response.ok) {
  770. throw new Error('Failed to fetch image');
  771. }
  772. return response.blob();
  773. });
  774. },
  775. //编辑源码
  776. toggleSourceMode() {
  777. if (!this.showHtml) {
  778. // 切换到源码模式,将编辑器内容同步到 textarea 中
  779. this.editorHtml = this.$refs.quillEditor.quill.root.innerHTML;
  780. this.showHtml = true; // 显示 textarea
  781. } else {
  782. // 切换回富文本模式,将 textarea 内容同步回编辑器
  783. this.showHtml = false; // 显示 Quill 编辑器
  784. // Quill 编辑器可能被销毁,所以使用 $nextTick 确保 DOM 渲染完成后再操作编辑器
  785. this.$nextTick(() => {
  786. if (this.$refs.quillEditor) {
  787. this.$refs.quillEditor.quill.root.innerHTML = this.editorHtml;
  788. } else {
  789. console.error('Quill 编辑器实例未找到');
  790. }
  791. });
  792. }
  793. }
  794. //富文本编辑器 end ------------------------------------------------------------>
  795. },
  796. watch: {
  797. 'form.type_id': {
  798. handler(newVal, oldVal) {
  799. if (newVal !== oldVal) {
  800. if (this.$route.query.id != undefined) {
  801. } else {
  802. console.log('-------新增--变化了------------');
  803. this.form.name = '';
  804. this.form.city_arr_id = [];
  805. this.form.city_id = '';
  806. this.form.cat_arr_id = '';
  807. this.form.website_id = '';
  808. this.form.catid = "";
  809. this.form.price = "";
  810. this.form.unit = "";
  811. this.form.min = null;
  812. this.form.max = null;
  813. this.form.islong = 0;
  814. this.form.validity = "";
  815. this.form.keyword = "";
  816. this.form.description = "";
  817. this.form.detail = "";
  818. this.form.hits = null;
  819. this.form.contact = '';
  820. this.form.phone = '';
  821. this.form.landline = '';
  822. this.form.email = '';
  823. this.form.postal = '';
  824. this.form.address = '';
  825. this.form.imgurl = [];
  826. this.form.city_id = '';
  827. }
  828. // 清空特定字段的数据
  829. if (newVal === 1) {
  830. // 从求购商品切换到供应商品
  831. this.form.price = '';
  832. console.log('供应商品');
  833. } else if (newVal === 2) {
  834. // 从供应商品切换到求购商品
  835. console.log('求购商品');
  836. }
  837. }
  838. },
  839. immediate: true // 立即执行一次
  840. },
  841. //监控 website_id
  842. // 若 website_id 发生变化,则清空 cat_arr_id 和 catid
  843. 'form.website_id': {
  844. handler(newVal, oldVal) {
  845. if (newVal !== oldVal) {
  846. this.form.cat_arr_id = [];
  847. this.form.catid = "";
  848. this.parentKey += 1;
  849. }
  850. },
  851. immediate: true // 立即执行一次
  852. }
  853. },
  854. mounted() {
  855. //1.判断是新建还是回显
  856. if (this.$route.query.id != undefined) {
  857. this.editId = this.$route.query.id;
  858. this.editStatus = true;
  859. this.tableDivTitle = "编辑商品";
  860. console.log("编辑商品")
  861. this.getMainData();
  862. } else {
  863. this.editStatus = false;
  864. console.log("添加商品!")
  865. }
  866. this.fetchWebsiteOptions();
  867. this.getUserInfo();
  868. //复制内容到富文本 start ------------------------------------------------------------>
  869. this.$nextTick(() => {
  870. const quillEditor = this.$refs.quillEditor.quill;
  871. if (quillEditor) {
  872. console.log('Quill 编辑器已初始化');
  873. // 在粘贴事件触发时,记录所有 img 的 src
  874. quillEditor.clipboard.addMatcher(Node.ELEMENT_NODE, (node, delta) => {
  875. if (node.tagName === 'IMG') {
  876. const imageUrl = node.getAttribute('src');
  877. console.log('检测到粘贴的图片 URL:', imageUrl);
  878. if (imageUrl && !imageUrl.startsWith('data:') && !imageUrl.startsWith('file://')) {
  879. // 先处理图片上传
  880. this.handleImageFromWeb(imageUrl).then((uploadedImageUrl) => {
  881. // 查找编辑器中所有 img 标签并替换 src
  882. const imgs = quillEditor.root.querySelectorAll('img');
  883. imgs.forEach((img) => {
  884. if (img.getAttribute('src') === imageUrl) {
  885. img.setAttribute('src', uploadedImageUrl); // 替换 src
  886. console.log('图片 src 已替换为:', uploadedImageUrl);
  887. }
  888. });
  889. });
  890. }
  891. }
  892. return delta; // 返回原始 delta
  893. });
  894. } else {
  895. console.error('Quill 初始化失败');
  896. }
  897. });
  898. //复制富文本 end ------------------------------------------------------------>
  899. },
  900. };
  901. </script>
  902. <style scoped lang="less">
  903. //文本编辑器
  904. .QuillTitle {
  905. line-height: 36px;
  906. font-size: 14px;
  907. color: #606266;
  908. font-weight: bold;
  909. padding-left: 30px;
  910. span {
  911. color: #ff4949
  912. }
  913. .QuillModelBtn {
  914. display: inline-block;
  915. margin-left: 10px;
  916. font-size: 12px;
  917. color: #999;
  918. cursor: pointer;
  919. }
  920. }
  921. .editor-container {
  922. height: 420px;
  923. padding-bottom: 20px;
  924. }
  925. .my-quill-editor {
  926. height: 320px;
  927. }
  928. .ql-editor {
  929. height: 320px;
  930. }
  931. /* 富文本对齐方式 */
  932. .ql-align-center {
  933. text-align: center;
  934. }
  935. .ql-align-right {
  936. text-align: right;
  937. }
  938. .ql-indent-1 {
  939. padding-left: 16px;
  940. }
  941. .ql-indent-2 {
  942. padding-left: 32px;
  943. }
  944. .ql-indent-3 {
  945. padding-left: 48px;
  946. }
  947. .ql-indent-4 {
  948. padding-left: 64px;
  949. }
  950. .ql-indent-5 {
  951. padding-left: 80px;
  952. }
  953. .ql-indent-6 {
  954. padding-left: 96px;
  955. }
  956. .ql-indent-7 {
  957. padding-left: 112px;
  958. }
  959. .ql-indent-8 {
  960. padding-left: 128px;
  961. }
  962. //执行v-deep穿透scope选择器 start------------------------------------------------------------>*/
  963. ::v-deep .custom-form-item>.el-form-item__label {
  964. line-height: 140px !important;
  965. }
  966. ::v-deep .custom-textarea .el-textarea__inner {
  967. resize: none;
  968. /* 禁止用户拖拽调整大小 */
  969. }
  970. ::v-deep .custom-align-right .el-form-item__label {
  971. text-align: right;
  972. /* 设置标签文字右对齐 */
  973. }
  974. ::v-deep .el-select {
  975. width: 100%;
  976. /* 禁止用户拖拽调整大小 */
  977. }
  978. ::v-deep .el-input-group__prepend {
  979. color: black !important;
  980. }
  981. .formLabelFloatBox {
  982. margin-bottom: 10px;
  983. position: relative;
  984. .formLabeladdIcon {
  985. position: absolute;
  986. right: 45px;
  987. top: 5px;
  988. width: 38px;
  989. height: 24px;
  990. }
  991. .formLabelDelIcon {
  992. position: absolute;
  993. right: 5px;
  994. top: 5px;
  995. width: 38px;
  996. height: 24px;
  997. }
  998. }
  999. //执行v-deep穿透scope选择器 end------------------------------------------------------------>*/</style>