Bootstrap

修改国际事件的方法

<template>
  <el-dialog v-model="visible" :title="title" @close="cancel" width="80%">
    <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="120px">
      <el-form-item label="模板类型:" prop="templateType">
        <el-radio-group v-model="dataForm.templateType">
          <el-radio :value="1" size="large" border>
            <div style="width: 100%;">全内容</div>
            <img src="@/assets/content1.jpg" alt="" style="width: 150px;height: 150px;" />
          </el-radio>
          <el-radio :value="2" size="large" border>
            <div style="width: 100%;">列表形式1</div>
            <img src="@/assets/list1.jpg" alt="" style="width: 150px;height: 150px;" />
          </el-radio>
          <el-radio :value="3" size="large" border>
            <div style="width: 100%;">列表形式2</div>
            <img src="@/assets/list2.jpg" alt="" style="width: 150px;height: 150px;" />
          </el-radio>
          <el-radio :value="4" size="large" border>
            <div style="width: 100%;">图文形式1</div>
            <img src="@/assets/imgtext1.jpg" alt="" style="width: 150px;height: 150px;" />
          </el-radio>
          <el-radio :value="5" size="large" border>
            <div style="width: 100%;">图文形式2</div>
            <img src="@/assets/imgtext2.jpg" alt="" style="width: 150px;height: 150px;" />
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="关联的子栏目:" prop="categoryId">
        <el-tree-select v-model="dataForm.categoryId" :data="optindata" :render-after-expand="false" class="inp-width" />
      </el-form-item>
      <el-form-item label="发布时间:" prop="publishTime">
        <el-date-picker v-model="dataForm.publishTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
      </el-form-item>
      <el-form-item label="排序: " prop="sort">
        <el-input-number v-model="dataForm.sort" :min="0" />
      </el-form-item>
      <div v-if="dataForm.templateType==2 || dataForm.templateType==3">
        <el-form-item label="标题名称:" prop="title">
          <el-input v-model="dataForm.title" style="width: 100%;"></el-input>
        </el-form-item>
        <el-form-item label="内容来源:" prop="source">
          <el-input v-model="dataForm.source" class="inp-width"></el-input>
        </el-form-item>
      </div>
      <div v-if="dataForm.templateType==1 || dataForm.templateType==2||dataForm.templateType==3" style="border: 1px solid #ccc;margin: 0 26px;">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
        <Editor style="height: 500px; overflow-y: hidden;" v-model="dataForm.content" :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
      </div>
      <div v-if="dataForm.templateType==4 || dataForm.templateType==5">
        <div style="padding:15px;margin:10px 0;border: 1px solid #ccc;" v-for="(item,index) in imgTextList" :key="index">
          <el-row>
            <el-col :span="2">上传图片</el-col>
            <el-col :span="5">
              <el-upload class="avatar-uploader" :action="uploadApi" :headers="uploadHeaders" :show-file-list="false" :on-success="(res) => handleSuccess(res, index)">
                <img v-if="item.imageUrl" :src="item.imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-col>
            <el-col :span="2">文字描述</el-col>
            <el-col :span="15">
              <el-input v-model="item.linkTitle" style="width: 100%;"></el-input>
            </el-col>
          </el-row>
        </div>
        <!-- <el-button type="primary" @click="imgTextList.push({imageUrl: '', linkTitle: ''})" style="width: 100%;font-size: 30px;">+</el-button> -->
      </div>
    </el-form>
    <template #footer>
      <el-button @click="cancel()">取消</el-button>
      <el-button type="primary" v-if="!dataForm.publishTime" @click="submit()">确定</el-button>
      <el-button type="primary" v-if="dataForm.publishTime" @click="submit()">定时发布</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, shallowRef, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { ElMessage } from 'element-plus/es'
import { allColumn, saveContent } from '@/api/allApi' //接口
import { treeSelect } from '@/utils/myMethod' //工具类
import '@wangeditor/editor/dist/css/style.css' //富文本编辑器引入样式
import { Editor, Toolbar } from '@wangeditor/editor-for-vue' //富文本编辑器引入
import { IEditorConfig } from '@wangeditor/editor' //富文本编辑器的
import cache from '@/utils/cache' //为了获取token

const emit = defineEmits(['resetList']) //子组件调父组件方法

const visible = ref(false)
const title = ref('新增')
const dialogType = ref('add') //弹窗类型
const rowDate = reactive({}) //行数据
const dataFormRef = ref()
const dataForm = reactive({
	title: '',
	templateType: 1,
	categoryId: '',
	source: '',
	linkTitle: '',
	imageUrl: '',
	content: '',
	sort: '',
	publishTime: ''
})
const dataRules = reactive({
	templateType: [{ required: true, message: '请输入类型', trigger: 'change' }],
	categoryId: [{ required: true, message: '请输入子栏目', trigger: 'change' }]
}) //表单验证
const optindata = reactive([] as any[]) //关联栏目列表
const imgTextList = reactive([{ imageUrl: '', linkTitle: '' }]) //图文列表
const uploadApi = ref(import.meta.env.VITE_API_URL + '/content/upload') //上传图片接口
const uploadHeaders = reactive({
	Accept: 'application/json, text/plain, */*',
	Authorization: cache.getToken()
}) //上传图片请求头

//弹窗初始化
const init = (type: string, row: any) => {
	visible.value = true
	dialogType.value = type
	getList()
	Object.assign(rowDate, row) //浅拷贝,将row赋值给rowDate,用以前直接=赋值的形式会报错
	if (type === 'add') {
		title.value = '新增'
	} else if (type == 'edit') {
		title.value = '编辑'
		//回显
		nextTick(() => {
			for (let key in dataForm) {
				dataForm[key] = row[key]
			}
			if (dataForm.templateType == 4 || dataForm.templateType == 5) {
				imgTextList[0].imageUrl = dataForm.imageUrl
				imgTextList[0].linkTitle = dataForm.linkTitle
			}
		})
	}
}
//获取栏目
const getList = () => {
	allColumn({ websiteId: Number(localStorage.getItem('WebsiteId')) }).then((res: any) => {
		if (res.code === 0) {
			//添加树选择器必要节点
			let arr = treeSelect(res.data, 'name', 'id')
			getDisable(arr)
			//用push的方法可以解决reactive定义的数组不能直接被赋值的问题,也可以选择包一层,或者用ref定义.value是可以的
			optindata.length = 0
			optindata.push(...arr)
		} else {
			ElMessage.success(res.msg)
		}
	})
}
//添加禁用
const getDisable = (array: any) => {
	for (let i = 0; i < array.length; i++) {
		const e = array[i]
		if (e.children && e.children.length > 0) {
			e.disabled = true
			getDisable(e.children)
		} else {
		}
	}
	return array
}

//富文本编辑器相关
const editorRef = shallowRef() // 编辑器实例,必须用 shallowRef
const mode = 'default' // 或 'simple'
const toolbarConfig = {}
const editorConfig: Partial<IEditorConfig> = { MENU_CONF: {} } // 初始化 MENU_CONF 属性
//富文本编辑器配置图片相关
editorConfig.MENU_CONF['uploadImage'] = {
	server: uploadApi.value,
	fieldName: 'file',
	//自定义请求头,获取token
	headers: uploadHeaders,
	// 单个文件上传成功之后
	onSuccess(file: File, res: any) {
		dataForm.imageUrl = res.data.url
	}
}
//富文本编辑器配置视频相关
editorConfig.MENU_CONF['uploadVideo'] = {
	server: uploadApi.value,
	fieldName: 'file',
	//自定义请求头,获取token
	headers: uploadHeaders,
	maxFileSize: 20 * 1024 * 1024
}
//富文本编辑器方法
const handleCreated = editor => {
	editorRef.value = editor // 记录 editor 实例,重要!
}

//文件上传成功回调
const handleSuccess = (res: any, index: number) => {
	imgTextList[index].imageUrl = res.data.url
}
//保存
const submit = () => {
	// console.log(dataForm.publishTime,'dataForm.publishTime')
// 假设 dataForm.publishTime 是一个 ISO 格式的日期字符串
	// const times = dataForm.publishTime;

	// // 创建一个 Date 对象
	// const date = new Date(times);

	// // 获取年、月、日、时、分、秒
	// const year = date.getFullYear();
	// const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,所以要加1,并填充两位数字
	// const day = String(date.getDate()).padStart(2, '0'); // 填充两位数字
	// const hours = String(date.getHours()).padStart(2, '0'); // 填充两位数字
	// const minutes = String(date.getMinutes()).padStart(2, '0'); // 填充两位数字
	// const seconds = String(date.getSeconds()).padStart(2, '0'); // 填充两位数字

	// // 格式化日期字符串
	// const formattedTime = `${year}-${month}-${day}-${hours}-${minutes}-${seconds}`;



	// dataForm.publishTime = formattedTime


		// 输出结果
		// console.log(	dataForm.publishTime , '	dataForm.publishTime ');
	dataFormRef.value.validate((valid: boolean) => {
		if (valid) {
			let obj = {
				...dataForm,
				tenantId: JSON.parse(localStorage.getItem('userInfo')).id, //租户id
				websiteId: Number(localStorage.getItem('WebsiteId')) //网站id
			}
			if (dialogType.value === 'edit') {
				obj.id = rowDate.id
			}
			for (let i = 0; i < imgTextList.length; i++) {
				const e = imgTextList[i]
				if (dataForm.templateType == 4 || dataForm.templateType == 5) {
					imgTextList[i] = { ...obj, ...e }
				} else if (dataForm.templateType == 1 || dataForm.templateType == 2 || dataForm.templateType == 3) {
					imgTextList[i] = { ...obj }
				}
			}
			saveContent(imgTextList).then((res: any) => {
				if (res.code === 0) {
					ElMessage.success('操作成功')
					emit('resetList')
					cancel()
				} else {
					ElMessage.success(res.msg)
				}
			})
		}
	})
	// location.reload()
}
//取消重置
const cancel = () => {
	visible.value = false
	imgTextList.length = 0
	imgTextList[0] = { imageUrl: '', linkTitle: '' }
	dataForm.content = '' //不知道为啥用resetFields()方法没有清空富文本编辑器内容
	dataFormRef.value.resetFields()
}

// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
	const editor = editorRef.value
	if (editor == null) return
	editor.destroy()
})
defineExpose({
	init
})
</script>
<style lang="scss" scoped>
.inp-width {
	width: 220px;
}
.el-radio.is-bordered.el-radio--large {
	height: auto;
}
::v-deep(.avatar-uploader .el-upload) {
	border: 2px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
::v-deep(.avatar-uploader .el-upload:hover) {
	border-color: #409eff;
}
::v-deep(.avatar-uploader-icon) {
	font-size: 28px;
	color: #8c939d;
	width: 150px;
	height: 150px;
	line-height: 150px;
	text-align: center;
}
::v-deep(.avatar) {
	width: 150px;
	height: 150px;
	display: block;
}
</style>

方法一



  <el-form-item label="发布时间:" prop="publishTime">
        <el-date-picker v-model="dataForm.publishTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
      </el-form-item>

方法二

	// console.log(dataForm.publishTime,'dataForm.publishTime')
// 假设 dataForm.publishTime 是一个 ISO 格式的日期字符串
	// const times = dataForm.publishTime;

	// // 创建一个 Date 对象
	// const date = new Date(times);

	// // 获取年、月、日、时、分、秒
	// const year = date.getFullYear();
	// const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,所以要加1,并填充两位数字
	// const day = String(date.getDate()).padStart(2, '0'); // 填充两位数字
	// const hours = String(date.getHours()).padStart(2, '0'); // 填充两位数字
	// const minutes = String(date.getMinutes()).padStart(2, '0'); // 填充两位数字
	// const seconds = String(date.getSeconds()).padStart(2, '0'); // 填充两位数字

	// // 格式化日期字符串
	// const formattedTime = `${year}-${month}-${day}-${hours}-${minutes}-${seconds}`;



	// dataForm.publishTime = formattedTime


		// 输出结果
		// console.log(	dataForm.publishTime , '	dataForm.publishTime ');


;