Visual data previews with Vue

Last modified: November 22nd, 2023

As a modern web framework, Vue is purpose-built to handle reactive components that re-render when their data changes. This power can be used to configure live editing within the CloudCannon CMS.

This guide will focus on components that use the Vue Composition API.

Requirements for data previews#

  • Components must have an output URL. If your site is built with Nuxt using the Nuxt Content module, components in the pages/ directory are a good example.
  • Components must get their data from a data/content file somewhere in your project. This is critical, as the Visual Editor cannot open the components themselves.
  • These data/content files must be configured as a CloudCannon Collection. See the CloudCannon Reader documentation for more information.
  • Components will need to use the Vue onMounted and onBeforeUnmount hooks.

Installation#

The CloudCannon Visual Editor connector is available on npm.

To install, run:

Shell
copied
npm i -D @cloudcannon/visual-editor-connector

Integration#

Below is a component with the bare minimum needed for live editing in the Visual Editing.

pages/[...slug].vue
copied
<script setup>
  import { onMounted, onBeforeUnmount, ref } from 'vue';
  import { onCloudCannonChanges, stopCloudCannonChanges } from '@cloudcannon/visual-editor-connector';

  const { page } = useContent(); 

  const pageData = ref(page.value); 

  onMounted(async () => {
    onCloudCannonChanges((latestValue) => {
      pageData.value = latestValue; 
    });
  });

  onBeforeUnmount(async () => {
    stopCloudCannonChanges(); 
  });
</script>

useContent() is a function that is provided by Nuxt Content's Document-driven mode. It fetches the file in the content/ directory that reflects the current URL. Replace this line with however you fetch page data.

Vue's ref function creates a mutable reactive object. Whenever the value of pageData changes, any component that relies on that data will re-render.

The onCloudCannonChanges() hook takes a callback function that is triggered whenever the page is edited in CloudCannon. For example, editing the front matter of the corresponding page in the Data Editor will run the code here. The callback takes the updated page data as a parameter, and assigns the new data to the pageData object.

Because pageData is reactive, this will re-render and display the updated component in the Visual Editor immediately.

This needs to be run in the onBeforeUnmount() hook to tear-down listeners before the component is destroyed.

You should be able to make these additions with no difference to your build output or production environment.

For an example integration, check out our Sendit Nuxt template. If you have any issues, please contact support, or raise an issue on the GitHub repository.

Related Articles

Open in a new tab