Skip to content

Instantly share code, notes, and snippets.

@DarkGhostHunter
Last active September 25, 2023 07:07
Show Gist options
  • Save DarkGhostHunter/c5c4ca49c8f3a02afd67ce96432e334b to your computer and use it in GitHub Desktop.
Save DarkGhostHunter/c5c4ca49c8f3a02afd67ce96432e334b to your computer and use it in GitHub Desktop.
Using Trix (WYSIWYG editor) with Vue 3
<template>
<div class="trix-editor">
<textarea
:id="formId"
type="hidden"
ref="input"
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
style="display:none;"
><slot /></textarea>
<trix-editor ref="trixEditor" :input="formId"></trix-editor>
</div>
</template>
<script setup>
import {onMounted, ref} from 'vue'
import Trix from 'trix'; // Needed to initialize its custom HTML element.
// Allows to update the default prop of v-model in the parent.
//
// @see https://vuejs.org/guide/components/events.html#usage-with-v-model
defineProps(['modelValue'])
defineEmits(['update:modelValue']);
const input = ref(null);
const trixEditor = ref(null);
// Generate a random ID for the form. This way we can have multiple Trix
// editors without collisions. We then pass the random id to the Trix
// Editor, and set the input with the same id so it can update it.
const formId = 'trix-input' + Math.random().toString(36).slice(2, 20);
onMounted(() => {
if (input.value.hasAttribute('autofocus')) {
input.value.focus();
}
});
defineExpose({ focus: () => input.value.focus() });
</script>
<style scoped>
// Needed for trix, unles you want it fugly.
@import 'trix/dist/trix.css';
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment