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

Issue with Intel XDK: the document.location.href is directing to an incorrect page

Hello Community of Developers, I have been experimenting with different methods but still haven't found a solution. In my project using Intel XDK, whenever I attempt to change the page using location.location.href = "#EndGame" or similar codes in Java ...

Using JavaScript to dynamically change the IDs of multiple select elements during runtime

I am facing an issue when trying to assign different IDs to multiple select elements at runtime. The number of select elements may vary, but I need each one to have a unique ID. Can anyone assist me in locating the select elements at runtime and assignin ...

Executing JavaScript in Rails after dynamically adding content through AJAX

Looking for advice on integrating JavaScript functions into a Rails app that are triggered on elements added to the page post-load via AJAX. I've encountered issues where if I include the code in create.js.erb, the event fires twice. However, removing ...

Observable in RxJS with a dynamic interval

Trying to figure out how to dynamically change the interval of an observable that is supposed to perform an action every X seconds has been quite challenging. It seems that Observables cannot be redefined once they are set, so simply trying to redefine the ...

How can I implement a Vue v-if directive in App.vue, while having a toggle button in a separate component?

I am facing an issue in my App.vue file where I have a v-if condition that is hiding a div when the data returns false. I want to implement a toggle functionality for this, but I would like to place the button in a different component that is imported into ...

What method can I use in pure Javascript to identify which day the week begins on, either Monday or Sunday, based on the

Can someone help me determine the start day of the week in local time using only Javascript? The start day could be Monday, Sunday, Saturday, or Friday. I came across this helpful resource on Stack Overflow: <firstDay day="mon" territories="001 AD AI ...

The property number will have no effect on the time

Currently, I am in the process of developing an audio player that includes essential functions such as backward, play, and forward buttons. Strangely enough, the backward function operates perfectly fine, but the forward button is not functioning properly ...

Retrieve only the initial tag content using jquery

My goal is to extract the "22" from the following code... <div class="left"> <a class="count-link" href="http://url1.com"> <span>22</span> users </a> <a class="count-link" href="http://url2.com"> <span>10</span ...

An error has been thrown stating that the function startTimer is not defined, despite the fact that it is clearly defined

const startBtn = document.querySelector('.startBtn'); const pauseBtn = document.querySelector('.pauseBtn'); const ResetBtn = document.querySelector('.resetBtn'); const time = document.querySelector('.time'); let sec ...

Tips for integrating angular signature functionality using fabricjs in the latest version of Angular (Angular 11)

After struggling to make paperjs and the angular-signature library work together, I was at my wit's end. But then, I stumbled upon a different solution that proved to be much better. I realized that posting the solution under the appropriate question ...

Switch body class when the navbar's collapse show class is toggled

There are numerous methods to accomplish this task, but I am seeking the most optimal and efficient approach. My goal is to toggle a custom body class when the .navbar-toggle triggers the .show class on the .navbar-collapse element. I'm hesitant abo ...

What is the best way to retrieve a document element in React when utilizing an external script?

In my React project, I have successfully implemented a chat button using an external script. However, I encountered an issue where I needed to hide the chat button on specific pages. Since I couldn't access the button's element using a ref, I res ...

"Enhance your Vue 3 app with real-time data using GraphQL and Apollo - Learn how to automatically update queries when

I am eager to learn how to create Vue 3 Apollo applications using queries and mutations. I have experience with the react useQuery hook, which automatically re-renders the component when the cached data changes due to mutations. I have experimented with: ...

Transfer information from session to vue-component

Within my routes file, I obtain the current user from the session and then render the profile HTML: app.get('/profile', isLoggedIn, function(req, res) { res.render('profile.html', { user : req.user // extract user ...

Why do I keep receiving values only from the initial form? What could be the issue?

I am facing an issue on my website with multiple forms. The problem arises when the "Save" button is clicked, as it continues to check the fields in the first form instead of the form where the button is located. Here is a snippet of my current Ajax scrip ...

Angular state correctly maps to the controller but is not reflected in the HTML

I'm currently in the process of setting up a basic Angular application, something I've done many times before. I have defined a home state and another state for a note-taking app, but I am facing an issue where neither state is displaying or inje ...

Unfolding the potential of variables in JSON.stringify with Node.js

I am currently developing a node.js API for my app, which includes a simple TCP server that accepts NDJSON (newline delimited JSON). However, I have encountered an issue with the JSON stringify method. The problem arises when I attempt to expand all variab ...

Troubleshooting: Issue with Vue-Router failing to load component

I have been in the process of developing a website using Vue and Vue-Router locally. Upon completion, I push my changes with git to the production server which updates the site files. Recently, I encountered an issue with a payment status page that is wor ...

What's the best way to display a component once a function has been executed?

My service controls the visibility of components using *ngIf! Currently, when I click a button, the service sets to true and the components appear instantly! I want the components to only show after a specific function has finished executing. This means I ...

What benefits does Observable provide compared to a standard Array?

In my experience with Angular, I have utilized Observables in the state layer to manage and distribute app data across different components. I believed that by using observables, the data would automatically update in the template whenever it changed, elim ...