Rapidly generate VueJS templates for quick display

Is there a way, similar to KnockoutJS, to easily render content from a template using an ID?

<script type="text/html" id="template-example"><span>Hello world!</span></script>

<div data-bind="template: '#template-example'"></div>

I have gone through the documentation but couldn't find a solution. I also attempted to create a component named quick-template where the template attribute used a value from props, but it didn't render anything. This might be because the template is bound before props are populated.

Running on Version 2.6.12

Answer №1

When dealing with Vue, the most reliable source of information can be found in the official documentation.


Theory:

The template plays a crucial role in each Vue component. Without a template (or a render function, which essentially serves as a template), a Vue component will not render properly.
Templates can be provided in various ways:

  • template: rawHTML (as an HTML string)
  • template: '#some-id' (where #some-id refers to a <template>,
    <script type="text/x-template">
    , or plain DOM element).
  • <template>content</template>
    -in Single File Components (SFCs)
  • render function (which returns an HTML string) and overrides any other form of providing a template
  • el: '#some-id', where the template consists of the .innerHTML of the DOM element with that id 1, 2.

I will skip discussing render functions as they may not be relevant for your current situation. Vue has the ability to parse both HTML and JSX. Additionally, Vue loader supports pre-processors, making it compatible with PUG by using a plugin.


Practice:

  1. Register the templates as components, assigning the desired template attribute along with any accompanying elements such as props, data, computed, methods, components, directives, filters, emits, watch, expose, compilerOptions, inheritAttrs, mixins, extends, and/or lifecycle hooks.

  2. Integrate these components into your application.

Demo 3:

Vue.component('some-list', {
  template: '#some-list',
  props: ['powers']
})

Vue.component('some-item', {
  template: '#some-item',
  props: ['value']
})

Vue.component('svg-example', { 
  template: '#svg-example'
})

new Vue({
  el: '#app',
  data: () => ({
    myComponents: ['some-list', 'svg-example'],
    powers: 8
  }),
  methods: {
    getPowers(comp) {
      return (comp === 'some-list') && Number(this.powers)
    }
  }
})
#app { 
  display: flex;
  justify-content: space-evenly;
}
#app input {
  height: min-content;
}
#app div > div {
  padding: 3px 7px;
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c6a69795c2e322a322d28">[email protected]</a>/dist/vue.min.js"></script>
<div id="app">
  <span v-text="powers"></span>
  <input type="range" v-model="powers" min="2" max="12">
  <component v-for="component in myComponents"
             :powers="getPowers(component)"
             :key="component"
             :is="component" />
</div>

<template id="some-list">
  <div>
    <some-item v-for="(item, key) in powers" :key="key" :value="item" />
  </div>
</template>

<template id="some-item">
  <div v-text="Math.pow(2, value)" />
</template>

<template id="svg-example">
  <svg version="1.1"
       xmlns="http://www.w3.org/2000/svg"
       xmlns:xlink="http://www.w3.org/1999/xlink"
       viewBox="0 0 300 200"
       width="300">
    <image href="https://picsum.photos/300/200" />
  </svg>
</template>

Same example 4, 5, but registering the components locally within the app instead of globally in Vue:

new Vue({
  el: '#app',
  components: { 
    SomeList: {
      template: '#some-list',
      props: ['powers'],
      components: {
        SomeItem: {
          template: '<div v-text="Math.pow(2, value)" />',
          props: ['value']
        }
      }
    },
    SvgExample: {
      template: '#svg-example'
    }
  },
  data: () => ({
    powers: 8
  })
})
#app { 
  display: flex;
  justify-content: space-evenly;
}
#app input {
  height: min-content;
}
#app div > div {
  padding: 3px 7px;
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99efecfcd9abb7afb7a8ad">[email protected]</a>/dist/vue.min.js"></script>
<div id="app">
  <span>{{powers}}</span>
  <input type="range" v-model="powers" min="2" max="12">
  <some-list :powers="Number(powers)"></some-list>
  <svg-example></svg-example>
</div>

<script type="text/x-template" id="some-list">
  <div>
    <some-item v-for="(item, key) in powers" :key="key" :value="item" />
  </div>
</script>

<!-- innerHTML of this hidden div is used as template -->
<div id="svg-example" style="display: none">
  <svg version="1.1"
       xmlns="http://www.w3.org/2000/svg"
       xmlns:xlink="http://www.w3.org/1999/xlink"
       viewBox="0 0 300 200"
       width="300">
    <image href="https://picsum.photos/id/4/300/200" />
  </svg>
</div>


Notes:

1 - Only effective inside new Vue({}).
2 - The placeholder (initial DOM element) gets replaced during Vue's mounting process, causing any prior event registrations on the element to be lost.
3 - Templates can exist anywhere in the DOM, not restricted to being inside the Vue app itself.
4 - More rigid (SomeItem component must be declared within SomeList component, otherwise <SomeList /> cannot utilize it - somewhat unexpected behavior).
5 - I made some tweaks between the two examples with alternate syntaxes for comparison purposes.

Answer №2

If you want to create a unique component, you can define a custom component and use the script tag's content as the template.

Vue.component('my-component', '#template-example');

Next, integrate this component into your Vue application like so:

<div id="app">
   <my-component></my-component>
</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

Unable to retrieve JSON data using jQuery

When working with jQuery to retrieve JSON data, I encountered an issue. After storing the data in a variable named "ajaxResponse," attempting to access specific data points resulted in an error stating that ajaxResponse.blah is not defined. Interestingly, ...

Is there a way to efficiently remove deleted files from my Google Drive using a customized script?

After creating a function in Google Scripts to clear my trashed files, I ran it only to find that nothing happened. There were no logs generated either. function clearTrashed() { var files2 = DriveApp.getFiles(); while (files2.hasNext()) { var c ...

Navigating through a multidimensional array in Angular 2 / TypeScript, moving both upwards and downwards

[ {id: 1, name: "test 1", children: [ {id: 2, name: "test 1-sub", children: []} ] }] Imagine a scenario where you have a JSON array structured like the example above, with each element potenti ...

Tips for utilizing a for loop within an array extracted from a jQuery element for automation

I am looking to streamline the process using a for loop for an array containing 10 image files in the parameters of initialPreview and initialPreviewConfig. My envisioned solution involves the following code snippet: for (i = 0; i < 11; i++) { "< ...

What is the process for exporting a plugin from dayjs() in JavaScript?

Currently, I have incorporated the plugin isToday() to enhance the capabilities of dayjs(). Nevertheless, I am uncertain about how to export isToday() in order to utilize it across other files. import isToday from "dayjs/plugin/isToday"; expor ...

Javascript recursive function calling itself

I've been struggling with the logic in my code and it seems like I've been staring at it for too long to spot the issue. A strange recursion occurs when this piece of code runs after a 30-second timeout, resulting in multiple GET requests to rese ...

Import components exclusively from the root/app directory in Angular 2

In my angular2 project, I used angular-cli version 1.0.0-beta.8 and angular version 2.0.0-rc.3. After running ng new or ng init, the directory structure created is as follows: create .editorconfig create README.md create src\app\app.compon ...

What is the most effective method for updating a className in Next.js using CSS Modules when a button is activated?

Looking to create a responsive navigation bar that transforms based on screen size? When the width reaches 600px, I'd like to hide the links and instead show a clickable nav button that reveals those options. Upon inspecting my list elements in the c ...

Running JavaScript in selenium and obtaining the result

I'm currently utilizing JavaScript with Selenium WebDriver. Here is a snippet of my code: let return_value = driver.execute_script(script) However, I am unsure how to retrieve the value from my script. const token = await grecaptcha.enterprise.exec ...

Tips for creating responsive content within an iframe

I have inserted a player from a website that streams a channel using an iframe. While I have managed to make the iframe responsive, the video player inside the iframe does not adapt to changes in viewport size. Despite trying various solutions found online ...

Utilizing Props in Vue.js to Access Data for v-model

After browsing online, I attempted to pass props to data in the following manner: Child Component: props: { idInput: { type: String, required: false }, nameInput: { type: String, required: false }, }, data() { return { id: this.idInput, na ...

The script file (.js) isn't showing up on the PHP or HTML webpage

Experiencing a peculiar issue and seeking advice on alternative solutions due to my limited experience in this matter. The Issue: I currently have the following script running smoothly: <script type="text/javascript" id="myscript" src="http://piclau ...

Calculate the number of parent nodes and their respective child nodes

I am curious about how I can determine the number of children nested within parent-child relationships. For example: const parent = document.querySelectorAll('.parent'); parent.forEach(el => { const ul = el.querySelector('.child3-chi ...

Whenever a click event is triggered, the Vue method is executed twice

Why is the set method being executed twice? Check the console when you click the star. Removing @click="set(rating)" results in no action, indicating it is not called elsewhere. http://jsfiddle.net/q22tqoLu/ HTML <div id="star-app" v-cloak> ...

Guide to automatically update div with new table rows with the help of Ajax

Can you assist me in updating the div called "table" that contains a table fetching rows from the database? <div id="table"> <h1 id="Requests"> <table></table> </h1> </div> <button id="refresh-btn"&g ...

Leveraging React Hooks' useEffect to trigger a prop callback function defined with useCallback

Currently, I am working on developing a versatile infinite scrolling feature using React Hooks along with the ResearchGate React Intersection Observer. The main concept revolves around a parent passing down a mapped JSX array of data and a callback functio ...

Issue with caching: Browser cache not being utilized even after implementing Cache-Control Header

First Requesthttps://i.sstatic.net/xtJCW.png Second Inquiryhttps://i.sstatic.net/4R9ln.png I have implemented a node module(express-cache-ctrl) to activate caching on a proxy. app.use(cache.public(3600)); Despite having Cache-control headers with max-age ...

The chosen element contains a value of -1

When the select element has a selected value of 4, form data is sent to the server and the controller returns a partial view. <script> $(document).ready(function () { var objSel = document.getElementById("IDVacationApplicationTyp ...

Expanding Grid Container in Material UI to Fill Parent Height and Width

Challenge I'm struggling to figure out how to make a Grid container element expand to the height and width of its parent element without directly setting the dimensions using inline styles or utilizing the makeStyles/useStyles hook for styling. I&ap ...

Steps for configuring Types in Graphql Codegen

I have successfully implemented a Vue 3 component that utilizes Urql to query a Hasura graphql endpoint. The query is functioning properly, but I am now focused on enhancing the type safety of the component. My approach involves using graphql Codegen to g ...