Utilize a pre-defined layout in a Vue component that is sent as a property

As a complete beginner, I kindly ask for your patience as I navigate through the coding basics.

I am looking to utilize a template specified in the prop. The template is located within the DOM. My intention for approaching it this way is to reuse the component logic (specifically pagination) while having the flexibility to modify how the template presents data on different pages. Therefore, I opted to separate the template from the script file.

Below is the HTML File snippet:

<div id="store-list">
  <paginated-list :list-data="stores" use-template="#displayList"></paginated-list>
</div>

<script type="text/template" id="display-list">
  <div>
    <div v-for="p in paginatedData">
      {{p.BusinessName}} 
    </div>
  </div>
</script>

And this is what's inside the .js file:

Vue.component('paginated-list', {
  data() {
    return {
      pageNumber: 0
    }
  },
  props: {
    listData: {
      type: Array,
      required: true
    },
    useTemplate: {
      type: String,
      required: false
    },
    size: {
      type: Number,
      required: false,
      default: 10
    }
  },
  computed: {
    pageCount() {
      let l = this.listData.length,
        s = this.size;
      return Math.floor(l / s);
    },
    paginatedData() {
      const start = this.pageNumber * this.size,
        end = start + this.size;
      return this.listData
        .slice(start, end);
    }
  },
  //template: document.querySelector('#display-list').innerHTML // this works
  template: document.querySelector(useTemplate).innerHTML // this does not
});

var sl = new Vue({
  el: '#store-list',
  data: {
    stores: [{
      "BusinessName": "Shop Number 1"
    }, {
      "BusinessName": "Shop Number 2"
    }, {
      "BusinessName": "Shop Number 3"
    }]
  }
});
var shoppingList = new Vue({
  el: '#shopping-list',
  data: {
    header: 'shopping list app',
    newItem: '',
    items: [
      '1',
      '2',
      '3',
    ]
  }
})

Your help and guidance are highly valued. Thank you.

Answer №1

To change the component's template dynamically during rendering, you can utilize the inline-template attribute. Here is an example:

<paginated-list :list-data="stores" inline-template>
  <div>
    <div v-for="p in paginatedData">
      {{p.BusinessName}} 
    </div>
  </div>
</paginated-list>

For more information, visit https://v2.vuejs.org/v2/guide/components-edge-cases.html#Inline-Templates

Even though your component may have a default template, using inline-template will override it if specified.

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 consolidating multiple projects under one domain without incurring any additional costs

Good morning! In my quest to host multiple projects on a single domain, specifically xyz.com, I am faced with a dilemma. I have an outdated personal developer portfolio created with React, and a newer software built with Vue.js that I would like to use fo ...

The functionality for tabbed content seems to be malfunctioning on Chrome and Firefox, however it works perfectly

In my index.js file, I have various functions set up like so: // a and b is placed at index.jsp $("#a").click(function (){ //this works on index.jsp and display.jsp(where the servlets forwards it). $("#b").load('servletA.html?action=dis ...

Navigate the JSON object at predetermined intervals, such as in the case of movie subtitles

Apologies if the title is not specific enough, open to any suggestions for improvement. Here's my issue: I have a JSON file (presented here as a JavaScript object) that contains subtitles for a movie. My goal is to display the text exactly as it appea ...

Error: Vue.js application requires the "original" argument to be a Function type

I am facing an issue when trying to call a soap webservice using the 'soap' module in my Vue SPA. Strangely, I encounter an error just by importing the module. Despite my extensive search efforts, I have not been able to find a solution yet. Her ...

A guide on iterating through an array in vue.js and appending a new attribute to each object

To incorporate a new property or array item into an existing virtual DOM element in Vue.js, the $set function must be utilized. Attempting to do so directly can cause issues: For objects: this.myObject.newProperty = "value"; For arrays: ...

Filtering Key Presses in Quasar: A Comprehensive Guide

Seeking Assistance I am looking to integrate an "Arabic keyboard input filtering" using the onkeyup and onkeypress events similar to the example provided in this link. <input type="text" name="searchBox" value="" placeholder="ب ...

Retrieving the <html> tag within an Angular component

In an Angular component, the <body> and <head> tags can be accessed by injecting DOCUMENT as shown below: import { DOCUMENT } from '@angular/common'; import { Inject } from '@angular/core'; export class TestComponent { c ...

Pop-up confirmation dialog in JQuery following an AJAX request

In order to validate on the server side whether a person with a specific registration number already exists in the database, I have implemented a process. If the person is found registered, the program flow continues as usual. However, if the number is not ...

Angular and Express: Automatically redirecting to the previous page after user login

A question similar in nature can be found here, although not directly relevant to my situation. Within my Single Page Application, I am implementing PassportJS for user authentication. There are multiple routes that necessitate user login. The routing is ...

Is it possible to include an if/else statement within a tailwind class in React components?

I want to dynamically change the background color of a div based on a condition. If the condition is true, I want the background color to be white; otherwise, I want it to be black. Despite trying to achieve this using an if/else statement, the background ...

The Angular Node server is responding with the error message "You have entered 'undefined' instead of a stream."

Using angular 9 + universal has been smooth sailing until I encountered an issue after building the app with npm run build:ssr and attempting to run it using node: node dist/app/server/main.js. The error message that popped up in the terminal was: Node ...

Submitting a form within AJAX-powered tabs (using the Twitter Bootstrap framework)

I have encountered an issue while trying to submit a form that is located within tabs. The content of these tabs is generated through AJAX. My problem arises when I submit the form - the page refreshes and loads the "default" tab, causing the PHP function ...

I want to use the enter key for posting, but also have the ability to use the shift and enter key to create a

$("#post_text").keydown(function(e){ // Checking if Enter key was pressed without shift key if (e.keyCode == 13) { // Prevent default behavior e.preventDefault(); } if (e.keyCode == 13 && !e.shiftKey) { alert('test'); } }); I a ...

What could be the reason for my button to update only at the completion of the "each" loop?

Is there a way to update the button text before the loop, so that users can receive feedback while it's running? Currently, the text only updates after the loop has completed. In my scenario, the button displays "Updating please wait..." after the lo ...

It can be frustrating to have to refresh the page twice in order to see changes when utilizing the revalidate feature in Next

When I make the REST call to fetch data for my page using the code below: // src/app/page.js const Home = async () => { const globalData = await getGlobalData(); return ( <main'> <SomeComponent data={globalData} /> < ...

When the button is clicked, bind the value to an object using the specified key in

I'm fairly new to Vue and I'm looking to generate buttons based on my data and show their information when clicked. The 'pets' object contains keys for id and info. (My actual data is more extensive and my code is a bit more complex, bu ...

A guide to reordering table rows by drag-and-drop with JavaScript

Seeking assistance with swapping table rows using JQuery UI. Although successful in the swap, struggling to retrieve row numbers during the drag and drop event. Understanding the row number is essential for subsequent tasks. Any help would be greatly appre ...

The condition in a Typescript function that checks for strings will never evaluate to true

I encountered a strange issue with a TypeScript condition in a function. Here is my current code, where the parameters are passed from outside: getLevel(validation: string, status: string): string { let card = ""; if (validation == &qu ...

When utilizing Ionic with Angular, it is difficult to access the hardware back button on mobile devices that have buttons located within the display/screen

When trying to access the hardware back button in my app, I encountered an issue where I couldn't produce an alert message to the user before the app closed. After posting a question on Stack Overflow (link of the question) and receiving help from the ...

Challenges arise when creating responsive map regions in Vue 3

I am currently working on a project in Vue 3 that involves an image map with click events on certain areas. The challenge I'm facing is that the images scale according to the browser size, but the coordinates of the image map are fixed pixel sizes. I& ...