v-model中update:modelValue
v-model的主要原因是由于value和input事件可能另有它用,
那么我们可不可以直接使用另外的属性和方法,而不需要去通过model进行定义。
vue3中就实现了这个功能,v-model绑定的不再是value,而是modelValue,接收的方法也不再是input,而是update:modelValue
写法:
<ChildComponent v-model:title="title" />
//或者
<ChildComponent :modelValue = "title" @update:modelValue = "title = $event">
// 或者
<ChildComponent :title="title" @update:title = "title = $event" />
使用:
父组件
<wm-tinymce
ref="editor"
v-model="data.introduction"
:min-height="400"
name="职能管理"
placeholder="请编辑职能大类"
/>
子组件
<div class="tinymce-container">
<editor
v-model="tinymceData"
:api-key="key"
:init="tinymceOptions"
:name="name"
:readonly="tinymceReadOnly"
/>
</div>
<script>
import { ref, watch, watchEffect } from 'vue'
import Editor from '@tinymce/tinymce-vue'
import { key, plugins, toolbar, setting } from './config'
export default {
name: 'WmTinymce',
components: { Editor },
props: {
modelValue: {
type: String,
default: '',
},
readOnly: {
type: Boolean,
default: false,
},
options: {
type: Object,
default() {
return { plugins, toolbar }
},
},
name: {
type: String,
default: '',
},
},
emits: ['update:modelValue'],
setup(props, { emit }) {
const tinymceData = ref(props.modelValue) // 编辑器数据
watch(
() => tinymceData.value,
(data) => emit('update:modelValue', data)
) // 监听富文本输入值变动
return {
tinymceData,
}
},
}
</script>
项目中使用: 富文本编辑器数据问题 父组件
<wm-tinymce
ref="editor"
v-model="data.introduction"
/>
子组件
<template>
<div class="tinymce-container">
<editor
v-model="tinymceData"
:api-key="key"
:init="tinymceOptions"
:name="tinymceName"
:readonly="tinymceReadOnly"
/>
</div>
</template>
<script>
import { ref, watch, computed, onMounted } from 'vue'
import tinymce from 'tinymce/tinymce'
import { setupPreview, setupWmPreview, setupIndent2em } from './plugins'
import { key, plugins, toolbar, setting } from './config'
import Editor from '@tinymce/tinymce-vue'
import Modal from './modal/index.vue'
export default {
name: 'WmTinymce',
components: {
Editor,
},
props: {
modelValue: {
type: String,
default: '',
},
},
emits: ['update:modelValue'],
setup(props, { emit }) {
const tinymceData = ref(props.modelValue) // 编辑器数据
watch(
() => props.modelValue,
(d) => (tinymceData.value = d)
)
watch(
() => tinymceData.value,
(data) => emit('update:modelValue', data)
) // 监听富文本输入值变动
return {
tinymceData,
}
},
}
</script>