在我的管理应用程序中,我在该组件中还有一个Vue 2的鹅毛笔丰富的编辑器,该编辑器使用v-model来存储其数据,现在我想将v-model从我的孩子vue-2-editor传递到我自己的父组件,文档说您可以在具有props值的组件中创建自定义v模型,并使用该值发出“输入”事件,但是如何将一个v模型传递给另一个模型(从子组件到父组件)。
我正在使用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的更多信息。
https://alligator.io/vuejs/add-v-model-support/
最佳答案
TL; DR
<vue-editor :value="value" @input="$emit('input' $event)" />
就像您说的那样,要在组件中支持
v-model
,您需要添加模型道具并发出模型事件,以使父级知道您要更新数据。默认情况下,
v-model
使用value
道具和input
事件,但是,从2.2.0+开始,您可以customize the component 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>
关于javascript - 在Vue中将v-model与嵌套组件一起使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58886181/