Passing your Craft CMS data to Vue.js with Twig

One of the unique challenges of using Vue JS with Craft CMS is how you get your data from Craft into Vue. Vue’s whole model of reactive UI is based on having your data in Vue, and your markup reacting to changes in that data automatically. That means Vue must ​“own” the data required for your templates and components. But, if your data lives in Craft, how do you get that data into Vue?

There are multiple ways to tackle this problem, and choosing the best way depends on how your project is structured. If your project is a Single Page Application (SPA) you’ll (most likely) need to create an API, and make HTTP requests to your API to get your data. But, if your project is a ​“traditional” server-side rendered website, then creating an API and delaying the render of your markup by waiting for an HTTP request to finish is usually not the best idea.

In this article, we’ll cover two ways you can pass your data into Vue using just Twig templates and Vue components.

Method #1: Passing your data into a component using props

Vue components have the ability to receive external data using props, which is convenient when using Vue components on your Craft site. Using this pattern allows you to pass your data from Twig into a component, whether it’s an object, array, string, or anything else. Here’s an example:

In the example above, we create two sets of data within our Twig templates: fruits (an array), and fruitEmoji (an object). Then we pass that data into our Vue component using props. Then in our JS, when we define our Vue component, we accept fruit and fruitEmoji both as props. Now the fruit and fruitEmoji data will be accessible within our Vue component.

Tip: Use the json_encode filter to escape your data and make it JS-readable, then use the raw filter to allow HTML entities so characters like quotes are printed correctly.

Method #2: Attaching data to the window, then loading it into Vue

Another way to pass your data into Vue from Craft is to assign it as a global variable in JavaScript, then load that data into your Vue component or instance. Consider the following example.