Seb*_*ski 6 vue.js vue-component vuejs2
我试图弄清楚如何从组件内部检测textarea上值的变化。
对于输入,我们可以简单地使用
<input
:value="value"
@input="update($event.target.value)"
>
Run Code Online (Sandbox Code Playgroud)
但是,在textarea上这将无法工作。
我正在使用的是CKEditor组件,当父组件(附加到此子组件)的模型值更新时,它应该更新所见即所得的内容。
我的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>
Run Code Online (Sandbox Code Playgroud)
我将其包含在父组件中
<html-editor
v-model="fields.body"
id="body"
></html-editor>
Run Code Online (Sandbox Code Playgroud)
但是,只要父组件的模型值发生更改-它不会触发观察程序-实际上就不会更新编辑器的窗口。
我只需要update()在父组件的模型fields.body更新时调用方法。
关于我该如何处理的任何指示?
这是相当多的代码需要破译,但我要做的是将文本区域和所见即所得 HTML 窗口分解为两个不同的组件,然后让父级同步值,因此:
文本区域组件:
<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
}
}
});
Run Code Online (Sandbox Code Playgroud)
我在这里所做的就是在输入发生变化时将输入发送回父级,我使用输入作为事件名称和value道具,以便我可以v-model在编辑器上使用。现在我只需要一个所见即所得的窗口来显示代码:
所见即所得窗口:
/**
* WYSIWYG window
*/
Vue.component('wysiwyg', {
template: `<div v-html="html"></div>`,
props: {
html: {
default: '',
type: String
}
}
});
Run Code Online (Sandbox Code Playgroud)
那里没有发生任何事情,它只是渲染作为 prop 传递的 HTML。
最后我只需要同步组件之间的值:
<div id="app">
<wysiwyg :html="value"></wysiwyg>
<editor v-model="value"></editor>
</div>
new Vue({
el: '#app',
data: {
value: '<b>Hello World</b>'
}
})
Run Code Online (Sandbox Code Playgroud)
现在,当编辑器发生更改时,它会将事件发送回父级,父级会进行更新value,然后在所见即所得窗口中触发该更改。这是整个操作过程: https: //jsfiddle.net/Lnpmbpcr/