gpt4 book ai didi

javascript - 在 Vue 中使用带有嵌套组件的 v-model

转载 作者:行者123 更新时间:2023-11-30 06:11:10 25 4
gpt4 key购买 nike

在我的管理应用程序中,我有一个,在这个组件中,我还有 Vue 2 的 quill rich 编辑器,它使用 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>

有关自定义组件中模型的更多信息。

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

最佳答案

长话短说

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

如你所说,支持v-model在一个组件中,您需要添加一个模型 Prop 并发出一个模型事件,让父级知道您想要更新数据。

默认 v-model使用 value Prop 和 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com