Using Vue.js: loading a template within an asynchronous component

Recently delving into , I am eager to set up a basic website using it. Each page (About Us, Contact Us, etc) has its corresponding component.

Here is my functional starting point

Vue.component('about-us', {
    template: '<div>...lots of markup...</div>'
});

My goal is to transition this code to work asynchronously. Following the documentation, I have attempted the following code:

Vue.component('about-us', function(resolve, reject){
    let template_string = '';

    // Load the template with ajax
    $.post(ajax_url, {'action': 'get_about_page'}, function(r){
        r = JSON.parse(r);

        // Save the template string
        if( r.success ) {
            template_string = r.data;
        }
    });

    // Resolve callback for Vue
    resolve({
        template: template_string
    });
});

The error message I am encountering is:

[Vue warn]: Failed to mount component: template or render function not defined. found in ---> Anonymous Root

Question: Am I approaching this incorrectly? Is it a syntax issue? I am uncertain if I am on the right track. (Yes, I have jQuery loaded)

Answer №1

To properly implement this code, ensure that your resolve function is within the ajax callback.

Vue.component('about-us', function(active, unaccepted){
    // Use ajax to load the template
    $.post(ajax_url, {'action': 'get_about_page'}, function(response){
        response = JSON.parse(response);

        // Store the template string
        if( response.success ) {
            // Activate resolve callback for Vue
            active({
              template: response.data
            });
        } else {
          unaccepted("Component definition failed!")
        }
    });
});

Answer №2

I am currently utilizing this code snippet:

Vue.component('about-us', function (resolve, reject) {
  $.post('ajax_url', {'action': 'get_about_page'}, 'html')
   .done(function (data) {
     resolve({template: data})
   })
})

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

Tips for dynamically loading fresh Google Adsense code with JavaScript without any user interaction

Recently, Google made a change in their ad code by replacing <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js</script> with <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygo ...

Add an input element to a form fieldset by employing vue

In my form, I have a staged approach with 3 fieldsets that only appear when the "Next" button is clicked. Now, in the third fieldset, I need to add input elements based on keys extracted from an external json object. Data: data: () => ({ c ...

Create the artwork on cube surfaces as a complete unit, rather than focusing on the individual triangles that form the face - three.js

While trying to paint each face of a cube with a different color, I came across a helpful thread that outlines a method to achieve this: var geometry = new THREE.BoxGeometry(5, 5, 5); for (var i = 0; i < geometry.faces.length; i++) { geometry.faces ...

Function is raising an error with the wrong value or text

I am currently testing a form that I am in the process of developing. My goal is to have different values returned each time I click on a different item from the dropdown menu. If this explanation isn't clear, please take a quick look at my pen for cl ...

MUI Tutorial: Displaying Text with Line Breaks

Whenever I input text into the MUI Textfield, it displays without any line breaks. Is there a more effective solution available? <Stack direction="row" alignItems="start" justifyContent="start" mb={5}> <TextFie ...

using VueJS, learn how to dynamically apply text to a data variable based on certain props

I'm facing an issue with conditional value assignment to the data variable based on props. The ternary operator is causing errors in my code. Here's a snippet for reference: <template> <div class="absolute left-3 top-1/2"> ...

Retrieving data from a remote PHP server using JavaScript

I am currently working on two separate websites. Site A is coded using only HTML and JavaScript, while site B utilizes PHP. I am trying to figure out a way to access variables from site B within site A. For example: The code for site A looks something li ...

Sending data through a form using AJAX and PHP

Greetings! I've developed a page that allows users to view results for a specific tournament and round. The user will first select a sport, which will then populate the available tournaments based on the sport selection. Following this, the user can ...

Do window.location.href and window.open interfere with each other?

I'm attempting to open a PDF in a new URL and redirect the user to the homepage at the same time. However, these two conditions in the "if" block are conflicting with each other. The page successfully redirects to the homepage, but the window.open() f ...

Exploring the functionality of arrays in Jest's cli option --testPathIgnorePatterns

Looking to exclude multiple folders, one in the src folder and another in node_modules, when using the --testPathIgnorePatterns option. Does anyone have an example of how to use this pattern effectively? I am unable to configure an array in the package.js ...

Using JavaScript to make an AJAX call to a different domain while bypassing the Content Security Policy restrictions

While parsing a web page, I need to initiate an AJAX call to my localhost depending on the content. The purpose is to exchange data using a PHP script on my localhost, possibly in JSON format (still under testing). This process is part of a plugin that I ...

React Higher Order Component (HOC) encountered an ESLint issue: spreading props is not

Does eslint lack intelligence? The Higher Order Component (HOC) is quite generic, so I struggle to specify the incoming options/props as they are dynamic based on the component being wrapped by this HOC at any given time. I am encountering an error statin ...

Encountered a 404 Error when attempting to store data in mongoDb using node.js and express

Currently, I am facing an issue while trying to save data from Bootstrap input fields into my MongoDB database. Every time I attempt to do so, I encounter the error insertMovie:1 POST http://localhost:3000/insertMovie 404 (Not Found). Despite my efforts to ...

Transferring a list from MVC ViewBag to JavaScript

I have a situation where I am passing a list of users from my controller to the view using the ViewBag. Now, I also need to pass this same list to the JavaScript on the page. One way I thought of doing this is by iterating through the list with a foreach l ...

Stop the page from scrolling when a modal is displayed in React

I've encountered an issue with my custom modal component where the background stops scrolling when the modal is open. Initially, I attempted to solve this by using the following code: componentDidMount() { document.body.style.overflow = 'hi ...

Counting the occurrence of a specific class within an element using jQuery

Within my table, each row is assigned one or more classes based on its region. This is the structure of my table: <table> <thead> <th>Title</th> <th>Name</th> </thead> <tbody> <tr class="emea ...

Using ObjectIDs in MongoDB may be successful, however, it may not function properly in Mongoose

The desired effect is successfully achieved by the first code snippet shown below: //in mongodb console: db.collection.update({"username":"name"}, {$pull : { "task" : { "_id" : ObjectId("55280205702c316b6d79c89c")}}}) However, the second code snippet wri ...

Issues with testing incorporating jest, react, webpack, and SVG

I recently delved into the world of React development, but I've hit a snag when trying to run a test with an SVG file. You can find the code in my GitHub repository https://github.com/alejomongua/react-playground. Upon running npm run test, I encoun ...

Json with ExtJs columns data is fully populated

I am having trouble with displaying columns in my jsp which fetches json data. I am retrieving this json data in my javascript and using Ext.data.JsonStore but the columns are not showing up as expected. Here is the code for the store: store = new Ext.da ...

Attempting to retrieve nested data, only to be met with an undefined response

I've been attempting to retrieve specific information by iterating through the SearchResult object like so: for (let productKey in SearchResult) { if (SearchResult.hasOwnProperty(productKey)) { products.push({ name ...