首页 > 解决方案 > 在 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 的更多信息。

https://alligator.io/vuejs/add-v-model-support/

标签: javascriptvue.js

解决方案


TL;博士

<vue-editor :value="value" @input="$emit('input' $event)" />

就像你说的,要支持v-model组件,你需要添加一个模型道具并发出一个模型事件,让父级知道你想要更新数据。

默认情况下v-model使用valueprop 和inputevent,但是,从 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>

推荐阅读