Build a Blog in Vue with Headless Oracle Content Management

Introduction

Vue.js is a progressive framework for building user interfaces. But what happens when you need a content management system (CMS) to serve all of your content? Fortunately, Oracle Content Management, with its rich headless CMS capabilities, has a graceful solution for your content administration and governance needs.

In this tutorial, we’ll build a simple blog in Vue by leveraging Oracle Content Management as a headless CMS as well as its software development kit (SDK) for content delivery in JavaScript. This Vue sample is available on GitHub.

The tutorial consists of three steps:

  1. Prepare Oracle Content Management
  2. Build the Blog in Vue
  3. Prepare your application for deployment

Prerequisites

Before proceeding with this tutorial, we recommend that you read the following information first:

To follow this tutorial, you’ll need:

What We’re Building

Our blog will consist of a three-page site that lets visitors explore blog articles organized into topics. The first page, the home page, will consist of branding (company name and logo), some links, and a list of blog topics.

To take a look at what we’re building, here’s the end state of our tutorial, a basic Vue blog that consumes content from Oracle Content Management:

https://headless.mycontentdemo.com/samples/oce-vue-blog-sample

This is what the home page will look like at the end of this tutorial:

This image shows the home page for Cafe Supremo demo site with a list of the available topics.

The second page, the topic page, shows previews of each blog article that belongs to the topic. Here’s how an individual topic page will look:

This image shows a topic page called ‘Recipes’ with a list of the available articles for that topic.

Lastly, the article page renders the final blog article, including information about the blog’s author. Here’s how an individual article page will look:

This image shows an individual article page, with the content and an author reference.

To proceed, you’ll need to have an active subscription to Oracle Content Management and be logged in with the Content Administrator role.

Step 1: Prepare Oracle Content Management

If you don’t already have an Oracle Content Management instance, see the Quick Start to learn how to register for Oracle Cloud, provision an Oracle Content Management instance, and configure Oracle Content Management as a headless CMS.

For this tutorial, you’ll need to create a content model in either of two ways. There’s a downloadable asset pack available that will fill your empty repository with content types and associated content, or you can create your own content model and content.

To prepare Oracle Content Management:

  1. Create a channel and asset repository.
  2. Create a content model using either of two methods:

Create a Channel and Asset Repository

You first need to create a channel and an asset repository in Oracle Content Management so you can publish content.

To create a channel and an asset repository in Oracle Content Management:

  1. Log in to the Oracle Content Management web interface as an administrator.

  2. Choose Content in the left navigation menu and then choose Publishing Channels from the selection list in the page header.

    This image shows the Publishing Channels option selected in the dropdown menu in the Content page header.

  3. In the upper right corner, click Create to create a new channel. Name the channel ‘OCEGettingStartedChannel’ for the purpose of this tutorial, and keep the access public. Click Save to create the channel.

    This image shows the publishing channel definition panel, with ‘OCEGettingStartedChannel’ in the channel name field.

  4. Choose Content in the left navigation menu and then choose Repositories from the selection list in the page header.

    This image shows the Repositories option selected in the dropdown menu in the Content page header.

  5. In the upper right corner, click Create to create a new asset repository. Name the asset repository ‘OCEGettingStartedRepository’ for the purpose of this tutorial.

    This image shows the repository definition panel, with ‘OCEGettingStartedRepository’ in the repository name field.

  6. In the Publishing Channels field, select the OCEGettingStartedChannel channel to indicate to Oracle Content Management that content in the OCEGettingStartedRepository repository can be published to the OCEGettingStartedChannel channel. Click Save when you’re done.

    This image shows the repository definition panel, with ‘OCEGettingStartedChannel’ in the Publishing Channels field.

Create a Content Model

The next step is to create a content model. You can use either of two methods:

Import the Oracle Content Management Samples Asset Pack

You can download a preconfigured Oracle Content Management sample assets pack that contains all required content types and assets for this tutorial. If you prefer, you can also create your own content model rather than download the sample assets pack.

You can upload a copy of the content we’re using in this tutorial from the Oracle Content Management Samples Asset Pack. This will let you experiment with the content types and modify the content. If you want to import the Oracle Content Management Samples Asset Pack, you can download the asset pack archive, OCESamplesAssetPack.zip, and extract it to a directory of your choice:

  1. Download the Oracle Content Management Samples Asset Pack (OCESamplesAssetPack.zip) from the Oracle Content Management downloads page. Extract the downloaded zip file to a location on your computer. After extraction, this location will include a file called OCEGettingStarted_data.zip.

  2. Log in to the Oracle Content Management web interface as an administrator.

  3. Choose Content in the left navigation menu and then choose Repositories from the selection list in the page header. Now select OCEGettingStartedRepository and click the Import Content button in the top action bar.

    This image shows the Repositories page, with the OCEGettingStartedRepository item selected.

  4. Upload OCEGettingStarted_data.zip from your local computer to the Documents folder.

    This image shows the upload confirmation screen for the OCEGettingStarted_data.zip file.

  5. Once it’s uploaded, select OCEGettingStarted_data.zip and click OK to import the contents into your asset repository.

    This image shows the selected OCEGettingStarted_data.zip file with the OK button enabled.

  6. After the content has been imported successfully, navigate to the Assets page and open the OCEGettingStartedRepository repository. You’ll see that all the related images and content items have now been added to the asset repository.

    This image shows the OCEGettingStartedRepository repository, with all assets that were just imported.

  7. Click Select All on the top left and then Publish to add all the imported assets to the publishing channel that you created earlier, OCEGettingStartedChannel.

    This image shows the OCEGettingStartedRepository repository, with all assets selected and the Publish option in the action bar visible.

  8. Before publishing, you need to validate all the assets. First add OCEGettingStartedChannel as a selected channel, and then click the Validate button.

    This image shows the Validation Results page, with the OCEGettingStartedChannel channel added in the Channels field, all assets to be validated, and the Validate button enabled.

  9. After the assets have been validated, you can publish all the assets to the selected channel by clicking the Publish button in the top right corner.

    This image shows the Validation Results page, with the OCEGettingStartedChannel channel added in the Channels field, all assets validated, and the Publish button enabled.

Once that’s done, you can see on the Assets page that all assets have been published. (You can tell by the icon above the asset name.)

This image shows the Assets page, with all assets pubished.

After importing the Oracle Content Management Samples Asset Pack, you can start building the blog in Vue.

Create Your Own Content Model

Instead of importing the Oracle Content Management Samples Asset Pack, you can also create your own content model.

For this tutorial, we’re using a content type called ‘OCEGettingStartedHomePage’ to build the home page for our blog. This home page consists of branding (company name and logo), some URLs for links, and a list of blog topics that should be included on the page.

This image shows the home page for the Cafe Supremo demo site.

To create content types for the content model:

  1. Log in to the Oracle Content Management web interface as an administrator.
  2. Choose Content in the left navigation menu and then choose Asset Types from the selection list in the page header.
  3. Click Create in the top right corner.
  4. Choose to create a content type (not a digital asset type). Repeat this for all required content types.

This image shows the Create Asset Type dialog in the Oracle Content Management web interface.

We’ll create four content types, each with its own set of fields:

The first content type, OCEGettingStartedHomePage, should have the following fields:

Display Name Field Type Required Machine Name
Company Name Single-value text field X company_name
Company Logo Single-value text field X company_logo
Topics Multiple-value reference field X topics
Contact URL Single-value text field X contact_url
About URL Single-value text field X about_url

This is what your OCEGettingStartedHomePage content type definition should look like:

This image shows the definition for the content type ‘OCEGettingStartedHomePage’. It includes these data fields: Company Name, Company Logo, Topics, Contact URL, and About URL.

The second content type, OCEGettingStartedTopic, should have the following field:

Display Name Field Type Required Machine Name
Thumbnail Single-value image field X thumbnail

This is what your OCEGettingStartedTopic content type should look like:

This image shows the definition for the content type ‘OCEGettingStartedTopic’. It includes this data field: Thumbnail.

The third content type, OCEGettingStartedAuthor, should have the following fields:

Display Name Field Type Required Machine Name
Avatar Single-value image field X avatar

This is what your OCEGettingStartedAuthor content type should look like:

This image shows the definition for the content type ‘OCEGettingStartedAuthor’. It includes this data field: Avatar.

The fourth and final content type, OCEGettingStartedArticle, should have the following fields:

Display Name Field Type Required Machine Name
Published Date Single-value date field X published_name
Author Single-value reference field X author
Image Single-value image field X image
Image Caption Single-value text field X image_caption
Article Content Single-value large-text field X article_content
Topic Single-value reference field X topic

This is what your OCEGettingStartedArticle content type should look like:

This image shows the definition for the content type ‘OCEGettingStartedArticlePage’. It includes these data fields: Published Date, Author, Image, Image Caption, Article Content, and Topic.

Once you’ve created your content types, you can add these content types to the repository that you created earlier, OCEGettingStartedRepository:

  1. Log in to the Oracle Content Management web interface as an administrator.
  2. Navigate to OCEGettingStartedRepository.
  3. Edit the repository and, under Asset Types, specify all four newly created content types. Click the Save button to save the changes.

This image shows the Edit Repository page in Oracle Content Management, with the four newly created content types associated with the OCEGettingStartedRepository repository.

After adding the content types to the repository, you can open the OCEGettingStartedRepository repository on the Assets page and start creating your content items for all the content types.

This image shows content items on the Assets page in the Oracle Content Management web interface, with options on the left for collections, channels, languages, types, content item selection, and status.

Step 2: Build the Blog in Vue

To consume our Oracle Content Management content in a server-side rendered Vue application, we can use the Vue blog sample, which is available as an open-source repository on GitHub.

Note: Remember that using the Vue sample is optional, and we use it in this tutorial to get you started quickly. You can also build your own Vue application.

To build the blog in Vue:

  1. Clone the sample repository and install dependencies
  2. Configure the Vue application
  3. Work with the Oracle Content Management Content SDK
  4. Use the Content SDK to Fetch Content

Clone the Sample Repository and Install Dependencies

The Vue blog sample is available as an open-source repository on GitHub.

You’ll first need to clone the sample from GitHub to your local computer and change your directory into the repository root:

git clone https://github.com/oracle/oce-vue-blog-sample.git
    cd oce-vue-blog-sample

Now that you have your code base, you need to download dependencies for the application. Run the following command from the root directory:

npm install

Configure the Vue Application

In this Vue blog sample, you need to configure a few pieces of information so that your Oracle Content Management Content SDK (and any other requests) can target the correct instance URL and API version with the correct channel token. These values are used in src/scripts/server-config-utils.js to instantiate a new delivery client.

This application uses an .env file that is read by Vue when it bundles the client and server applications. The vue.config.js file is an optional configuration file used by Vue when building applications. By using webpack. DefinePlugin in this configuration file, any values read from the .env file can be made available to anywhere in the application.

Open the .env file in a text editor. You’ll see the following information:

# The connection details for the Oracle Content Management server to be used for this application
    SERVER_URL=https://samples.mycontentdemo.com
    API_VERSION=v1.1
    CHANNEL_TOKEN=47c9fb78774d4485bc7090bf7b955632

Change each key-value pair to reflect your instance URL, the API version you want to target, and the channel token associated with your publishing channel. The channel for this tutorial is OCEGettingStartedChannel.

The other setting in the file is the port on which your server application will run. Adjust the setting according to your environment.

# The port the Express Server is to run on
    EXPRESS_SERVER_PORT=8080

Work with the Oracle Content Management Content SDK

Oracle Content Management offers an SDK to help discover and use content in your applications. The SDK is published as an NPM module, and the project is hosted on GitHub.

Learn more about the SDK here.

The SDK has been registered as a runtime dependency of this project in the package.json file.

Use the Content SDK to Fetch Content

We can now leverage the Content SDK to fetch content so that we can render it in our Vue application.

The src/scripts folder contains the code for getting data from Oracle Content Management using the Content SDK.

The src/scripts/server-config-utils.js file imports the Content SDK and then creates a delivery client using the configuration specified in .env.

The following command imports the SDK:

import { createDeliveryClient, createPreviewClient } from '@oracle/content-management-sdk';

The following command creates the delivery client:

return createDeliveryClient(serverconfig);

The src/scripts/services.js file contains all the code to get data for the application. There’s one main function for each page component in the application to get all the data for that page.

For rendering the images, the services.js provides a helper method to retrieve the sourceset for an asset that is constructed from the renditions for the asset.

function getSourceSet(asset) {
      const urls = {};
      urls.srcset = '';
      urls.jpgSrcset = '';
      if (asset.fields && asset.fields.renditions) {
        asset.fields.renditions.forEach((rendition) => {
          addRendition(urls, rendition, 'jpg');
          addRendition(urls, rendition, 'webp');
        });
      }
      // add the native rendition to the srcset as well
      urls.srcset += `${asset.fields.native.links[0].href} ${asset.fields.metadata.width}w`;
      urls.native = asset.fields.native.links[0].href;
      urls.width = asset.fields.metadata.width;
      urls.height = asset.fields.metadata.height;
      return urls;
    }

Home Page Data

The home page requires several data calls to get all of its data:

  1. First we query for items in the channel specified in .env.
  2. For each of the topic items, we fetch its details.

Open src/scripts/services.js and find the getTopicsListPageData() function, which gets all of the data for the home page.

export function getTopicsListPageData() {
      const client = getClient();
    
      return fetchHomePage(client)
        .then((data) => (
          getRenditionURLs(client, data.logoID)
            .then((renditionUrls) => {
              data.companyThumbnailRenditionUrls = renditionUrls;
              return data;
            })
        ));
    }

The fetchHomePage() function, called by the getTopicsListPageData() function, gets all the items in the channel. This gets the logo ID, the company name, the about and contact URLs, and a list of topics.

function fetchHomePage(client) {
      return client.queryItems({
        q: '(type eq "OCEGettingStartedHomePage" AND name eq "HomePage")',
      }).then((data) => {
        const logoID = data.items[0].fields.company_logo.id;
        const title = data.items[0].fields.company_name;
        const aboutUrl = data.items[0].fields.about_url;
        const contactUrl = data.items[0].fields.contact_url;
    
        const { topics } = data.items[0].fields;
        const promises = [];
    
        topics.forEach((origTopic) => {
          // add a promise to the total list of promises to get the full topic details
          promises.push(
            fetchTopic(client, origTopic.id)
              .then((topic) => topic),
          );
        });
    
        // execute all the promises returning a single dimension array of all
        // of the topics and the other home page data
        return Promise.all(promises)
          .then((allTopics) => (
            {
              logoID,
              companyTitle: title,
              aboutUrl,
              contactUrl,
              topics: flattenArray(allTopics),
            }
          )).catch((error) => logError('Fetching topics failed', error));
      }).catch((error) => logError('Fetching home page data failed', error));
    }

The fetchTopic() function is then called for each topic ID to get the full topic details.

function fetchTopic(client, topicId) {
      return client.getItem({
        id: topicId,
        expand: 'fields.thumbnail',
      }).then((topic) => {
        topic.renditionUrls = getSourceSet(topic.fields.thumbnail);
        return topic;
      }).catch((error) => logError('Fetching topic failed', error));
    }

getTopicsListPageData() also calls getRenditionURLs() to get the URL of the image to render.

function getRenditionURLs(client, identifier) {
      return client.getItem({
        id: identifier,
        expand: 'fields.renditions',
      }).then((asset) => getSourceSet(asset))
        .catch((error) => logError('Fetching Rendition URLs failed', error));
    }

Topic Page Data

The topic page receives a topic ID and requires several data calls to get all of its data:

  1. Get all the articles for the specified topic.
  2. For each article, get its rendition URLs.

Open src/scripts/services.js and find the fetchTopicArticles(topicId) function, which is used to get all of the data for the topic page.

export function fetchTopicArticles(topicId) {
      const client = getClient();
      return client.queryItems({
        q: `(type eq "OCEGettingStartedArticle" AND fields.topic eq "${topicId}")`,
        orderBy: 'fields.published_date:desc',
      }).then((data) => {
        const promises = [];
        const articles = data.items;
    
        articles.forEach((article) => {
          // add a promise to the total list of promises to get the article url
          promises.push(
            getRenditionURLs(client, article.fields.image.id)
              .then((renditionUrls) => {
                article.renditionUrls = renditionUrls;
                return {
                  ...article,
                };
              }),
          );
        });
    
        // execute all the promises and return all the data
        return Promise.all(promises)
          .then((allArticles) => ({
            topicId,
            articles: flattenArray(allArticles),
          }));
      }).catch((error) => logError('Fetching topic articles failed', error));
    }

The fetchTopicArticles() method also uses the getRenditionURLs() as seen previously, to get the image for the article.

Article Page Data

The article page receives an article ID and requires several data calls to get all of its data:

  1. Get the article details for the specified article. For each article, get its rendition URLs.
  2. Get the rendition URLs for the author avatar.

Open src/scripts/services.js and find the fetchArticleDetails(articleId) function, which gets the data for the article page.

export function fetchArticleDetails(articleId) {
      const client = getClient();
      return client.getItem({
        id: articleId,
        expand: 'fields.author,fields.image',
      }).then((article) => {
        const title = article.fields.author.name;
        const date = article.fields.published_date;
        const content = article.fields.article_content;
        const imageCaption = article.fields.image_caption;
        const { name } = article;
        const renditionUrls = getSourceSet(article.fields.image);
        const avatarID = article.fields.author.fields.avatar.id;
        // Get the author's avatar image
        return getRenditionURLs(client, avatarID)
          .then((authorRenditionUrls) => (
            // return an object with just the data needed
            {
              id: articleId,
              name,
              title,
              date,
              content,
              imageCaption,
              renditionUrls,
              authorRenditionUrls,
            }
          ));
      }).catch((error) => logError('Fetching article details failed', error));
    }

The fetchArticleDetails() method also uses the getRenditionURLs() as seen previously, to get the avatar image.

Now that we have our data queries, we can render the responses in our Vue components.

Client-Side Versus Server-Side Rendering

With client-side rendering (CSR), the client is responsible for building and rendering the content of a web page using JavaScript. With server-side rendering (SSR), the whole page is built on the server, and a complete web page is returned to the client.

When the web page is requested from the server in client-side rendering, the HTML document returned contains skeleton HTML and no actual content. It contains a reference to a JavaScript bundle, which the client then requests from the server. On receiving this bundle, the client executes the JavaScript and populates the web page. Until the client has finished executing the JavaScript, all the user sees is a blank web page. One downside of client-side rendered applications is that when some web crawlers index the site, there is no actual content to index.

With server-side rendering (SSR), the whole page is built on the server, and a complete web page is returned to the client. The advantage of this is that web crawlers can index the entire content on the web page.

Vue Blog Application Flow

The flow of the Vue blog application is as follows:

  1. The client makes a request to the server for a given route. The server application’s entry point is an Express server.
  2. The Express server receives the request and then performs the following tasks:
    1. It creates a fresh Vue application instance using a factory function.
    2. This factory function will determine which components will be rendered for the given route and call its serverPrefetch function to get all the data for each component. The data is stored in a Vuex store.
    3. When the fresh Vue application instance has been created, the Express server will create a string of all the content to render.
    4. The HTML for the document to return to the client is generated. It contains the following information:
    • The string of content to render
    • A script tag containing the client-bundle.js that the client will need
    • The data obtained from all the components stored in Vuex, serialized out into JSON
    1. The Express server then returns the HTML to the client.
  3. The client receives the HTML and renders it. The user will see a fully formed web page.
  4. The client gets the serialized data from the browser window and creates a client-side Vuex store with that data.
  5. The client requests the client-bundle.js file from the server. After receiving it, the client runs the JavaScript in the bundle.
    • It “hydrates” the HTML, adding in any client-side JavaScript, such as click listeners.
    • Each component being rendered sees if its data is in the Vuex store. If the data is not present, the component makes a server call to get the data. Note that data will not be present if client-side navigation and client-side rendering have occurred. If the page is server-rendered, the data will be present.

If a page has been rendered on the server side, then you can view the source of the web page to see all the content in the HTML.

Server-Side Express Server and Rendering

The server application makes use of an Express server to receive the request, generate a Vue application instance, generate the HTML page, and return the response.

The Express server file is located at src/server/server.js.

The Express server accepts all requests and then creates the Vue application instance, the router and the Vuex store. Vue server-renderer’s renderToString is used to get a string representation of the components required to render the route. This in turn would call that component’s serverPrefetch method to get that component’s data and populate the Vuex store.

The index.html file is read and the Vue content and the serialized data from the Vuex store is added to the markup. During the build process Vue will have already added the references to the client JavaScript bundles and the generated stylesheet.

The generated HTML document is then returned to the client.

server.get('*', async (req, res) => {
      // create the root app, router and vuex store
      const { app, router, store } = await buildApp(req.url);
    
      // wait for the router to be ready
      router.push(req.url);
      await router.isReady();
    
      // get the application content for the current route
      const appContent = await renderToString(app);
    
      // read the index.html template file
      fs.readFile(path.join('./', clientDistPath, 'index.html'), (err, html) => {
        if (err) {
          throw err;
        }
    
        // Serialize out the Vuex Store
        const storeData = serialize(store.state);
        const renderState = `
          <script>
            window.INITIAL_DATA = ${storeData}
          </script>`;
    
        // replace the app tag in the HTML with the app content string and serialized data
        html = html.toString().replace(
          '<div id="app"></div>',
          `<div id="app">${appContent}</div>${renderState}`,
        );
    
        // set any headers on the response before returning
        res.setHeader('Content-Type', 'text/html');
        res.send(html);
      });
    });

The file src/app.js contains the code to create the Vue application for the client or for the server.

const isSSR = typeof window === 'undefined';
    
    export default function buildApp() {
      const app = (isSSR ? createSSRApp(App) : createApp(App));
    
      app.use(router);
      app.use(store);
    
      return { app, router, store };
    }

When the client receives the HTML, the data will be made available in the window and the client will request the client bundle from the server.

Client-Side Rendering

The client-side rendering is located in src/client/main.js. This client-side code uses the function in src/app.js to create the relevant application before getting the serialized data from the window and place it in the Vuex store.

const { app, router, store } = buildApp();
    
    const storeInitialState = window.INITIAL_DATA;
    if (storeInitialState) {
      store.replaceState(storeInitialState);
    }

Note: If a user navigates to a page using client-side routing, server-side rendering will not occur. Instead, the content will be rendered using client-side rendering. As a result, the window will not contain any data, and the client will have to make a server call to get it.

After the app is created and mounted, the client will add in any client-side JavaScript code. This process is called hydrating.

router.isReady()
      .then(() => {
        app.mount('#app', true);
      });

Vue Components

The Vue components in this application contain the markup to define the views and JavaScript to populate the data in the views.

The next few sections provide an overview of how Vue renders our data in each of our components:

Router File

In our site, we want to provide three routes:

The src/router/index.js file defines the routes for the application. The articles list page takes an argument provided by Oracle Content Management in its URL for the selected topic. The article details page also takes an argument provided by Oracle Content Management in its URL for the selected article.

const routes = [
      {
        path: '/',
        name: 'home',
        component: TopicsListPage,
      },
      {
        path: '/articles/:topicId',
        name: 'articles',
        component: ArticlesListPage,
      },
      {
        path: '/article/:articleId',
        name: 'article',
        component: ArticleDetailsPage,
      },
      {
        path: '/:pathMatch(.*)*',
        component: PageNotFound,
      },
    ];

This file also contains a factory function to create the router, which will be used in both server-side and client-side rendering.

Vuex File

The Vuex file, located at src/vuex/index.js, defines the Vuex store, data structures, actions, and mutations.

It imports the APIs from the services.js file to get the data required in the application.

import { getTopicsListPageData, fetchTopicArticles, fetchArticleDetails } from '../scripts/services';

The store’s state contains three members, one for storing all the data for each page in the application.

state: () => ({
      topicsListPageData: {},
      articlesListPageData: {},
      articleDetailsPageData: {},
    }),

The store contains three actions for getting the data for each page in the application.

actions: {
      // get the data for the home page
      getTopicsListPageData({ commit }) {
        return getTopicsListPageData()
          .then((data) => {
            commit('setTopicsListPageData', data);
          });
      },
    
      // get the data for the Image Grid Page
      fetchTopicArticles({ commit }, categoryId) {
        return fetchTopicArticles(categoryId)
          .then((data) => {
            commit('setArticlesListPageData', data);
          });
      },
    
      // get the data for the Image Grid Page
      fetchArticleDetails({ commit }, categoryId) {
        return fetchArticleDetails(categoryId)
          .then((data) => {
            commit('setArticleDetailsPageData', data);
          });
        

Finally, the store contains three mutations for storing the data for each page in the application.

mutations: {
      setTopicsListPageData(state, data) {
        state.topicsListPageData = data;
      },
    
      setArticlesListPageData(state, data) {
        state.articlesListPageData = data;
      },
    
      setArticleDetailsPageData(state, data) {
        state.articleDetailsPageData = data;
      },
    },

TopicsListPage Component

Any component in the pages directory is a route for the application. Any data required for a route must be obtained by these root components.

The Home page consists of a list composed of individual topics. It is rendered by the TopicsListPage component, located at src/pages/TopicsListPage.vue.

The component has three computed data members, which get data from the Vuex store needed in the component.

computed: {
      topicsListPageData() {
        return this.$store.state.topicsListPageData;
      },
      topics() {
        return this.$store.state.topicsListPageData.topics;
      },
      aboutUrl() {
        return this.$store.state.topicsListPageData.aboutUrl;
      },
    },

During server-side rendering, serverPrefetch() is called. It returns a promise to get the data from the Oracle Content Management server and stores the promise in the Vuex store.

serverPrefetch() {
      return this.fetchData();
    },
    
    methods: {
      fetchData() {
        // return the Promise from the action
        return this.$store.dispatch('getTopicsListPageData');
      },
    }

During client-side rendering, mounted() is called. If the data has not already been obtained, it gets the data from the Oracle Content Management server and stores it in the Vuex store.

if (!(this.topicsListPageData && this.topicsListPageData.topics)) {
      this.loading = true;
      this.fetchData()
        .then(() => {
          this.loading = false;
        });
    }

When the component renders, it gets all the data from the component’s computed members.

Header Component

The TopicsListPage component uses the Header component to display the company title, company logo, and the Contact Us/About Us links.

It is located at src/components/Header.vue and receives all of its data as properties. It does not get any additional data from the server.

TopicsListItem Component

The TopicsListPage component uses the TopicsListItem component to display the individual topic in the list.

The TopicsListItem component, located at src/components/TopicsListItem.vue, receives all of its data as properties. It does not get any additional data from the server.

ArticlesListPage Component

The Topic page displays the articles in the topic whose ID is passed into the component on the URL. It is rendered by the ArticlesList component, located at src/pages/ArticlesListPage.vue.

This component has one computed data member, which gets data needed in the component from the Vuex store.

computed: {
      articles() {
        return this.$store.state.articlesListPageData.articles;
      },
    },

During server-side rendering, serverPrefetch() is called. It returns a promise to get the data from the Oracle Content Management server and stores the promise in the Vuex store.

serverPrefetch() {
      return this.fetchData();
    },
    
    methods: {
      fetchData() {
        // return the Promise from the action
        return this.$store.dispatch('fetchTopicArticles', this.topicId);
      },
    }

During client-side rendering, mounted() is called. If the data has not already been obtained, this function gets the data from the Oracle Content Management server and stores it in the Vuex store.

if (this.$store.state.articlesListPageData.topicId !== this.topicId
     || !this.articles) {
      this.loading = true;
      this.fetchData()
     .then(() => {
       this.loading = false;
     });
    }

When the component renders, it gets all the data from the component’s computed members.

ArticlesListItem Component

The ArticlesListPage component uses the ArticlesListItem component to display the individual articles in the list.

The ArticlesListItem component is located at src/components/ArticlesListItem.vue and receives all of its data as properties. It does not get any additional data from the server.

ArticleDetailsPage Component

The Article page displays details of the article whose ID is passed on the URL. It is rendered by the ArticleDetails component, located at src/pages/ArticleDetailsPage.vue.

The component has three computed data members, which get data needed in the component from the Vuex store.

computed: {
      article() {
        return this.$store.state.articleDetailsPageData;
      },
      formattedDate() {
        const article = this.$store.state.articleDetailsPageData;
        return article && article.date ? `Posted on ${dateToMDY(article.date.value)}` : '';
      },
      cleanContent() {
        const article = this.$store.state.articleDetailsPageData;
        const { content } = article;
        const options = {
          stripIgnoreTag: true, // filter out all HTML not in the whitelist
         stripIgnoreTagBody: ['script'], // the script tag is a special case, we need to filter out its content
        };
        return filterXSS(content, options);
      },
    },

During server-side rendering, serverPrefetch() is called. It returns a promise to get the data from the Oracle Content Management server and stores the promise in the Vuex store.

serverPrefetch() {
      return this.fetchData();
    },
    
    methods: {
      fetchData() {
        // return the Promise from the action
        return this.$store.dispatch('fetchArticleDetails', this.articleId);
      },
    }

During client-side rendering, mounted() is called. If the data has not already been obtained, the function gets it from the Oracle Content Management server and stores it in the Vuex store.

if (this.$store.state.articleDetailsPageData.id !== this.articleId
        || !this.article) {
      this.loading = true;
      this.fetchData()
        .then(() => {
          this.loading = false;
        });
    }

When the component renders, it gets all the data from the component’s computed members.

Step 3: Prepare Your Application for Deployment

Now that we’ve built our Vue blog site, we need to see it in a local development server so we can debug any issues and preview the application before it goes live.

Prepare the application for deployment in three steps:

  1. Build the application
  2. Run the application using Node
  3. Use scripts to build and run the application in development and production

Build the Application

Vue’s vue-cli-service is used to build the application. Two bundles need to be built, one to run on the server and one to run on the client.

The optional vue.config.js file used to configure the builds, such as the location of the built bundles and the entry points for the client and server applications.

To build the application run the following command:

npm run build

This will build the client bundle using:

vue-cli-service build

And will build the server bundle using:

cross-env SSR=1 vue-cli-service build

The SSR environment variable tells vue.config.js file to build the server bundle.

Run the Application Using Node

Once the bundles have been created, you can start the server by running the node command:

node dist/server/serverBundle.js

Use Scripts to Build and Run the Application in Development and Production

The package.json file, located at the root of the project, contains scripts that make it easier to build the bundles and run the application.