我正在设法从组件中检测到textarea上的值的变化。
对于输入,我们可以简单地使用
<input
:value="value"
@input="update($event.target.value)"
>然而,在文本区域,这是行不通的。
我正在使用的是CKEditor组件,它应该在更新父组件的模型值(附加到这个子组件)时更新wysiwyg的内容。
我的Editor组件当前如下所示:
<template>
<div class="editor" :class="groupCss">
<textarea :id="id" v-model="input"></textarea>
</div>
</template>
<script>
export default {
props: {
value: {
type: String,
default: ''
},
id: {
type: String,
required: false,
default: 'editor'
}
},
data() {
return {
input: this.$slots.default ? this.$slots.default[0].text : '',
config: {
...
}
}
},
watch: {
input(value) {
this.update(value);
}
},
methods: {
update(value) {
CKEDITOR.instances[this.id].setData(value);
},
fire(value) {
this.$emit('input', value);
}
},
mounted () {
CKEDITOR.replace(this.id, this.config);
CKEDITOR.instances[this.id].setData(this.input);
this.fire(this.input);
CKEDITOR.instances[this.id].on('change', () => {
this.fire(CKEDITOR.instances[this.id].getData());
});
},
destroyed () {
if (CKEDITOR.instances[this.id]) {
CKEDITOR.instances[this.id].destroy()
}
}
}
</script>我将它包含在父组件中。
<html-editor
v-model="fields.body"
id="body"
></html-editor>但是,每当父组件的模型值发生变化时--它不会触发观察者--实际上就没有更新编辑器的窗口。
我只需要在更新父组件的模型update()时调用fields.body方法。
任何关于我如何接近它的指针?
发布于 2017-07-09 10:55:05
这是一段需要解密的代码,但我要做的是将文本区域和所见即所得HTML窗口分解为两个不同的组件,然后让父元素同步这些值,因此:
TextArea组件:
<template id="editor">
<textarea :value="value" @input="$emit('input', $event.target.value)" rows="10" cols="50"></textarea>
</template>
/**
* Editor TextArea
*/
Vue.component('editor', {
template: '#editor',
props: {
value: {
default: '',
type: String
}
}
});这里我所做的就是在输入发生变化时将输入发回父程序,我使用输入作为事件名,使用value作为支柱,这样我就可以在编辑器上使用v-model。现在我只需要一个wysiwyg窗口来显示代码:
WYSIWYG窗口:
/**
* WYSIWYG window
*/
Vue.component('wysiwyg', {
template: `<div v-html="html"></div>`,
props: {
html: {
default: '',
type: String
}
}
}); 没有什么可做的,它只是将作为支柱传递的HTML呈现出来。
最后,我只需要同步组件之间的值:
<div id="app">
<wysiwyg :html="value"></wysiwyg>
<editor v-model="value"></editor>
</div>
new Vue({
el: '#app',
data: {
value: '<b>Hello World</b>'
}
})现在,当编辑器更改时,它会将事件发送回父进程,父进程更新value,然后触发更改为wysiwyg窗口的事件。下面是正在执行的全部操作:https://jsfiddle.net/Lnpmbpcr/
https://stackoverflow.com/questions/44995186
复制相似问题