February 20, 2019
How to reuse Trix WYSIWYG editor with Vue.js

The problem

I fell in love with the Trix WYSISYG editor while using it in Basecamp. I’ve used many editors over the years, but they’ve all come with their own type of headache. While getting Trix up and running is fairly simple, I did run into a problem when trying to reuse the editor inside a modal that updates certain information. You can pass existing content into the editor via the value attribute on the related input field, but it doesn’t update automatically when the value updates. I was also using the editor twice on the same page, but dynamically passing the id attribute into the component using props was causing the editor to not render. So, I essentially had 2 problems to solve.

The solution

Let’s first tackle having Trix update when the value changes. First we’ll create a wrapper component since we’ll be reusing the editor in multiple places. We’ll use attribute binding in Vue.js to update the value when it changes outside the component.

<wysiwyg :value="variable-containing-value"></wysiwyg>

Next, we’ll use a custom watcher to listen for the updates and call the loadHTML method on the editor instance. While we’re at it, let’s solve the custom id issue as well.

<template>
  <div>
    <input :id="`trix-input-${_uid}`" type="hidden" :value="value">
    <trix-editor ref="trix" :input="`trix-input-${_uid}`"></trix-editor>
  </div>
</template>

<script>
  import Trix from 'trix';

  export default {
    props: ['value'],
    watch: {
      value (value) {
        value = value === undefined ? '' : value;
        if (this.$refs.trix.innerHTML !== value) {
          this.$refs.trix.editor.loadHTML(value);
        }
      }
    }
  };
</script>

In the code above, I used the private _uid that Vue uses to identify the component. This is not recommended, but it is a solution to get a unique identifier to use in your components. The reason I don’t recommend this is because it’s a private property and it could eventually change with a future update. There are many tools and functions available with a quick google search to generate unique ids in your components.

Hope this helps!

Copyright © 2022 Allan Kiezel – Long Island Web Designer & App Developer. All rights reserved.