javascript - 在 Vue 中使用带有嵌套组件的 v-model
问题描述
在我的管理应用程序中,我有一个,在这个组件中,我还有 Vue 2 的 quill 丰富的编辑器,它使用 v-model 作为其数据,现在我想将 v-model 从我的子 vue-2-editor 传递给我自己的父组件,文档说您可以在您的组件中使用 props 值自定义 v-model 并使用该值发出“输入”事件,但是如何将一个 v-model 从子组件传递到父组件。
我使用 vue 2 编辑器,使用 Vue.js 和 Quill 的文本编辑器: https ://github.com/davidroyer/vue2-editor
我的组件:
<template>
<div style="width:auto; height:auto; display:flex; flex-direction.column;">
<button @click="editorVisible = true">Show Editor</button>
<vue-editor v-model="value" :editorToolbar="customToolbar" useCustomImageHandler @imageAdded="handleImageAdded"></vue-editor>
</div>
</template>
<!--SCRIPTS-->
<script>
import { VueEditor } from 'vue2-editor';
export default {
name: 'ADMINeditor',
props:
{
value:{ required:true, type:String }
},
data()
{
return {
editorVisible:false
}
},
methods:
{
wrote()
{
this.$emit('input', this.value);
}
}
}
</script>
<!--STYLES-->
<style scoped>
</style>
我希望能够做到:
<admin-editor v-model="text"></admin-editor>
有关自定义组件中的 -model 的更多信息。
解决方案
TL;博士
<vue-editor :value="value" @input="$emit('input' $event)" />
就像你说的,要支持v-model
组件,你需要添加一个模型道具并发出一个模型事件,让父级知道你想要更新数据。
默认情况下v-model
使用value
prop 和input
event,但是,从 2.2.0+ 开始,您可以自定义组件v-model
。
该<vue-editor>
组件使用v-model
默认属性和事件,因此它需要一个属性并在数据更新时value
发出一个事件。input
所以:
<vue-editor v-model="value" />
相当于:
<vue-editor :value="xxx" @input="onXxxUpdate"
您的<admin-editor>
组件也需要支持v-model
,因此您需要执行与<vue-editor>
组件相同的操作,添加模型属性并发出模型事件。
然后,每当组件发出input
事件时发出事件。<admin-editor>
<vue-editor>
input
<template>
<vue-editor :value="value" @input="onEditorUpdate" />
</template>
<script>
import { VueEditor } from 'vue2-editor'
export default {
name: 'AdminEditor',
props: {
value: {
type: String,
default: '',
},
},
methods: {
onEditorUpdate(newVal) {
// ^^^^^^
// <vue-editor> input event payload
this.$emit('input', newVal)
},
},
}
</script>
推荐阅读
- java - 创建名为“entityManagerFactory”的 bean 时出错,无法正常运行 App
- unity3d - 如何在运行时存储或读取动画剪辑数据?
- java - 如何在 OpenGL 中沿 x 或 y 轴旋转时修复奇怪的对象拉伸?
- python - 如何以指定格式很好地打印出元素列表?
- silverstripe - 运行多个版本的 Silverstripe 对象
- python - 如何在numpy中跨多个轴连接多个数组
- javascript - 使用详细信息和摘要标签作为可折叠的内联元素
- django - 如何使用渲染将数据加载到 Django 模板中,并使用 AJAX 请求过滤加载的数据?
- swagger-ui - 如何使 Swagger UI 中的响应示例与 application/application/vnd.api+json 的实际响应相匹配?
- c# - 获取 Quartz.NET 3.0 中的所有工作