Skip to content
Advertisement

Vue3 – Ace Editor on v-model change

I am using Ace Editor with Vue3:

<v-ace-editor
    v-model:value="currentRecord.prompt"
    lang="json"
    theme="textmate"
    style="height: 100%;"
    :options="{
        showGutter: pipeline.input_mode!=='text',
        showPrintMargin: false,
        useWorker: true,
    }"
/>

It’s being initialized like this:

<script setup>
import {computed, ref, watch} from 'vue';
import {VAceEditor} from 'vue3-ace-editor';
import ace from 'ace-builds';
import 'ace-builds/src-noconflict/mode-json';
import 'ace-builds/src-noconflict/theme-textmate';
import workerJsonUrl from 'file-loader?esModule=false!ace-builds/src-noconflict/worker-json.js';
ace.config.setModuleUrl('ace/mode/json_worker', workerJsonUrl);

//Load in a set of different JSON texts:
const props = defineProps({
    records: {
        type: Object,
    },
});

let currentRecordIndex = ref(0)

let currentRecord = computed(() => collect(props.records).slice(currentRecordIndex.value).first() ?? {'prompt': ''})

</script>

Now, I want to automatically persist the value of currentRecord.prompt in my database on the backend. To do this, I was thinking of firing of a request to the backend every time the value of currentRecord.prompt was changed in the editor:

watch(() => currentRecord, () => {
    console.log("Current record was changed.");
    //Code to hit the backend comes here.
});

The problem here is that the watch doesn’t work/trigger whenever a change is made to the text in the editor.

Advertisement

Answer

As I am watching an object, I need to enable the deep option like so:

watch(currentRecord, () => {
    //...
}, {deep: true})

As using deep can be expensive (see official statement):

Deep watch requires traversing all nested properties in the watched object, and can be expensive when used on large data structures. Use it only when necessary and beware of the performance implications.

I figured I just needed to watch the value (since currentRecord is computed):

watch(currentRecord.value, () => {
    //...
})
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement