The error message generated by Nuxt.js when encountering an issue with dynamic components is "To resolve this issue, either compile the templates into render functions beforehand or utilize the compiler-in

Encountering an issue in Nuxt.js that states:

[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

found in

---> <Anonymous>
       <RenderPost> at components/RenderPost.vue
         <Pages/post/Id.vue> at pages/post/_id.vue
           <Nuxt>
             <Layouts/default.vue> at layouts/default.vue
               <Root>

The code structure was based on examples from: and the RenderPost.vue component looks similar to this:

<template>
    <client-only>
        <component :is="dynamicComponent" />
    </client-only>
</template>

<script>
export default {
    methods:
    {
        linkedView()
        {
            return `<a href="#" @click.prevent="runSomething">Click me</a>`;
        },

    },
    computed :
    {
        dynamicComponent() {
            return {
                data() { return { foo : null }},
                template : `<div>${this.linkedView()}<br>{{ foo }}</div>`,
                methods :
                {
                    runSomething()
                    {
                        this.foo = 'ran something!'
                    }
                }
            }
        }
    }
}
</script>

The <client-only> block was added to address issues related to server-side rendering and client-side rendering mismatch. Removing it leads to another error message stating:

[Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. Bailing hydration and performing full client-side render.

Answer №1

In Nuxt, the default configuration includes only the Vue runtime (excluding the compiler) to optimize build size by approximately 10KB. This is based on the assumption that most users utilize precompiled templates like single file components. However, using string templates at runtime may trigger a warning with the Vue runtime-only build.

If your application requires string templates at runtime, you will need to adjust Nuxt settings to use the Vue build that includes the compiler:

// nuxt.config.js
export default {
  build: {
    extend(config) {
      config.resolve.alias.vue = 'vue/dist/vue.common'
    }
  },
}

Answer №2

Explained below is the functionality of

<component :is="dynamicComponent"></component>
.

  • Two components are globally registered with Vue.
  • Upon clicking a button, the :is binding is dynamically updated with one of the registered component names.
  • The components emit an event back to the parent when a button is clicked.

Vue.component('Comp1', {
  template: `
    <div>
      COMPONENT 1<br />
      <button
        @click="() => $emit('clicked', 1)"
      >
        Click 1
      </button>
    </div>
  `
})

Vue.component('Comp2', {
  template: `
    <div>
      COMPONENT 2<br />
      <button
        @click="() => $emit('clicked', 2)"
      >
        Click 2
      </button>
    </div>
  `
})

new Vue({
  el: "#app",
  data() {
    return {
      dynamicComponent: 'Comp1'
    }
  },
  methods: {
    toggleComponent() {
      if (this.dynamicComponent === 'Comp1') {
        this.dynamicComponent = 'Comp2'
      } else {
        this.dynamicComponent = 'Comp1'
      }
    },
    handleClicked(id) {
      console.log('click in comp', id)
    }
  },
  template: `
    <div>
      <button
        @click="toggleComponent"
      >
        SWITCH COMPONENT
      </button>
      <br />
      <component
        :is="dynamicComponent"
        @clicked="(id) => handleClicked(id)"
      ></component>
    </div>
  `
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

There was an issue loading the map on an HTML code that was returned from an ajax request

I'm currently working on building my own personal website, which is also my first webpage, and I'm encountering some difficulties with displaying a Google map. Here's a breakdown of my situation: my webpage consists of four links that load ...

Using the .get() method to retrieve Firebase documents results in an error message saying "'is not a function'"

I'm currently attempting to retrieve all the documents from a specific collection in Firebase using the following code snippet: const userCollectionRef = collection(db, currentUser?.uid) const snapshot = await userCollectionRef.get() for (const doc of ...

Using node.js to stub an asynchronous function from a module that is required by a different module using proxy

Module being tested: 'use strict'; const config = require('config'); const q = require('q'); class RedisAccess { static getValue(key) { let deferred = q.defer(); if (config.redis.disableInteraction) ...

What is the reason behind the failure to update the state via a reducer and Object.assign?

I'm attempting to develop a reducer without utilizing ES6. It's an outmoded PHP application that lacks a build process for transpilation. I am initializing the state: let defaultState = { accountTypes: { individual: { c ...

Hot reloading with Webpack keeps HTML5 audio playing without interruption

Playing background music in a Vue app using the audio tag: <audio id="music" autoplay loop> <source :src="musicfilename" type="audio/mp3" /> </audio> Everything works smoothly, but encountering an issue during development r ...

Issue with jQuery Ready Event Not Triggering Following AJAX Load

Excuse me, could you help me with something? I have tried to find an answer for this issue but it is still not working. Here are my scripts: $(document).ready(function() { $('.gifs').gifplayer(); }); I also have dynamic content loaded by AJAX ...

Processing JSON data by reading multiple files using Node.js

I've encountered a situation where I have multiple files containing data with time stamps. It's important for me to read these files in order, line by line. However, I noticed that most Node packages utilize asynchronous methods for file reading. ...

Angular: Delaying the return until the $http request has successfully completed

I am facing a challenge in my main module where I need to create a service that can parse a json file and store its contents in an array. The intention is to make this array easily accessible by all controllers. However, the issue arises because the func ...

Transforming a div into image data with the power of jQuery

I am facing a challenge with my HTML page. I have implemented a button that is supposed to convert the entire HTML page into an image when clicked. So far, I have used html2canvas for this purpose as shown below: html2canvas([document.getElementById(&apos ...

How can I prevent a form from being submitted by pressing the 'Enter' key in Reactjs?

Is there a way to prevent form submission when I press the 'Enter' key after entering something? How can this be achieved? class Application extends React.Component { render() { return ( <div> <form> < ...

Tips for simulating a DOM element in Jasmine so that it is accessible to the controller

Trying to simulate a DOM element in my jasmine test it('Testing radio button change', function () { simElement = angular.element("<div><input class='my_radio' type='radio' /></div>"); si ...

The onClick event's detail property is persisting even after the React component has been replaced

In the onClick event, the value of event.detail indicates the number of clicks, with a double-click having event.detail = 2. It seems that when the React component being clicked is replaced, the event.detail value does not reset. This could be due to Reac ...

Obtaining a file (zip) from one source and transferring it to another source

Trying to transfer a zip file from one endpoint to another via a FE VueJS app resulted in corruption upon upload. The download and upload process can be achieved using fileSaver, but the goal is to eliminate the need for saving the file onto a hard drive a ...

To activate a function, simply click anywhere on the body: instruction

One of my latest projects involved creating a directive that allows users to click on a word and edit it in a text box. Once edited, clicking anywhere on the body should return the word back to its updated form. html <div markdown>bineesh</div& ...

Avoid page refreshing when modifying app.js in React

Today is only my second day using React and I started by creating a React app with "npx create-react-app." However, when I tried to make changes to the app.js file, they didn't appear on the page even after refreshing the browser multiple times. (My n ...

The React initialization and construction process leads to excessive memory consumption

Hi there, I am facing an issue while trying to start or build my React app as it keeps giving me a heap out of memory error. Despite adding the --max_old_space_size=8192 flag to my script, the problem persists. yarn run v1.22.5 $ react-scripts --max_old_ ...

The error message "NgFor only supports binding to Iterables such as Arrays" is triggered even though the JSON response is formatted as an array

Using TypeScript in CompanyComponent Class export class CompanyComponent { apiService : APIService; data : any; private companyUrl = 'http://localhost:4000/api/company/'; constructor(apiService : APIService) { this.apiService = api ...

What causes my backend to crash when incorrect credentials are entered?

Whenever I input incorrect credentials on my login page, it causes the backend to crash. I want to avoid this situation and prevent my backend from crashing. Can somebody please assist me in identifying and rectifying the mistake? I am using MongoDb as my ...

Having trouble getting express-handlebars to render an HTML page

I am currently working through a NodeJS tutorial that teaches how to display an HTML page, but I'm facing difficulties in making it function properly. I have installed all the necessary requirements and used the `--save` option to save it within my `n ...

Sending axios post requests in succession in Vue.js

I need to execute two post requests, where the second one should only be triggered after the first one receives a response. I tried using async/await but didn't find a satisfactory solution. let changed = false; if(//condition){ changed = true; ...