Split vue.js templates into individual files

Is there a way to modify this code in Vue.js to achieve the following:

<template type="login" />

<template type="subscribe" />

<template id="login">
  <label>Username</label>
  <input placeholder="Enter your username" key="username-input">
</template>

<template id="subscribe">
  <label>Email</label>
  <input placeholder="Enter your email address" key="email-input">
</template>

Allowing templates to be called by their IDs

For example, using them in events:

<template v-if="type === 'new_user'">
 <span>welcome {{ username }}</span>
</template>

<template v-if="type === 'user_confiremd'">
 <span>You have full access {{ username }}</span>
</template>

It would be ideal to do something like this:

<template v-for="event in events" :event="event" />

Answer №1

It seems like the beginning of some questionable practices...

In order to improve your code, consider creating two separate components and utilizing the relevant one based on the type variable.

You have the option to manage the component either through routing or using a dynamic component approach.

Here is an example of how this can be structured:

<component :is="type" />

References:

Answer №2

For those looking to conditionally utilize different templates, here is a practical demonstration utilizing Vue2's dynamic components:

new Vue({
  el: '#app',
  data: {
    type: 'login',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e7828a868e8bc9949e8984a7829f868a978b82c984888a">[email protected]</a>',
    dataFromChildren: {parentData: {email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff899d96919bbf9a879e928f939ad19c9092">[email protected]</a>'}}
  },
  components: {
    login: {
      template: '#login',
      props: ['email'],
      data: function() { return { watchedEmail: this.email } },
      watch: { watchedEmail: function() { this.$emit('update:email', this.watchedEmail); } }
    },
    subscribe: {
      template: '#subscribe',
      props: ['parentData']
    }
  }
});
<script src="https://unpkg.com/vue"></script>

<template id="login">
  <div>
    <label>Username</label>
    <input placeholder="Enter your username" key="username-input" v-model="watchedEmail">
  </div>
</template>
<template id="subscribe">
  <div>
    <label>Email</label>
    <input placeholder="Enter your email address" key="email-input" v-model="parentData.email">
  </div>
</template>

<div id="app">
  <component v-bind:is="type" :email.sync="email" v-bind="dataFromChildren"></component>

  <hr>
  <button @click="type = 'login'">login template</button>
  <button @click="type = 'subscribe'">subscribe template</button>
  
  <p>Edited via e-mail.sync [login component] (good practice): {{ email }}</p>
  <p>Edited via nested props [subscribe component] (bad practice): {{ dataFromChildren }}</p>
</div>

An issue to note is that templates must have a single root component due to a requirement from Vue, otherwise, an error Component template should contain exactly one root element. will occur.

Additionally, as the templates act as components, data must be passed to them using props. The code above demonstrates two methods of sending and receiving data. The :e-mail.sync approach is recommended as the best practice in this scenario.

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 showing a universal loading indicator for every axios request in a Nuxt plugin

Is there a way to implement a custom loading feature for all axios requests globally? I've developed a plugin for axios that can be used like this: plugins/axios.js export default function ({ app, $axios, redirect, store }, inject) { $axios ...

What are effective ways to eliminate script tags from a webpage?

I have implemented tags on my website that users can use to interact with the site. My goal is to figure out how to make the browser only read text from a specific file I write, without any HTML. This should be restricted to certain sections of my websit ...

Prevent elements from displaying until Masonry has been properly set up

My goal is to merge Masonry elements with existing ones. Currently, the items appear before Masonry initializes then quickly adjust into position a moment later. I want them to remain hidden until they are in their proper place. This is the snippet (with ...

When an array is prototyped as a member of a JavaScript object, it becomes a shared property among all instances

Is anyone else surprised by this behavior? It really caught me off guard... I was expecting prototyped arrays to be private to each instance of a class rather than shared across all instances. Can someone confirm if this is the intended behavior and provi ...

Inspecting the Ace Editor within the onbeforeunload event handler to confirm any modifications

I'm attempting to utilize the $(window).on('beforeunload', function(){}); and editor.session.getUndoManager().isClean(); functions within the ace editor to detect whether a user has made modifications to a document without clicking the submi ...

Ways to make JavaScript cycle through a set of images

I'm having trouble trying to set up a code that will rotate multiple images in a cycle for an image gallery I'm working on. So far, I've only been able to get one image to cycle through successfully. Any help or suggestions would be greatly ...

Incorporate a JavaScript library into a personalized JavaScript file that is utilized within my Angular2 project

Integrating Machine Learning into my Angular2 project using the "synaptic.js" JavaScript library is my goal. After executing the command npm install synaptic --save I intend to execute a custom javascript file (myJsFile.js): function myFunction() { v ...

How can I simulate the response of a VueX action using Vue-test-utils?

I am currently developing a test for a Vue component that interacts with a module store to execute an action and utilize the result from it. Since the action involves making requests to our API, I prefer not to run the test using the actual action. Instea ...

Guide to making a Java Servlet for a specific jQuery.ajax () request?

In one of my files named wfd.proxy.js, I have the following code snippet: if (!WFD) { var WFD = {}; }; if (!WFD.Proxy) { WFD.Proxy = {}; }; WFD.Proxy = { SERVICE_URL : "/delegate/WFD/WFService?", PDF_SERVICE_URL : "/delegate/pdf-exporter?", ...

Generating an interactive button click feature within a cell of a data table

Can someone help me figure out why I am getting a SyntaxError when trying to trigger a function in a datatable cell using an onclick event on a button? The button is successfully created, but the error occurs when clicking it. The problem seems to lie wit ...

Using a variable to store the value of the id attribute in HTML code

How can I dynamically add an ID attribute to an HTML element using a variable declared in JavaScript? Using jQuery var table_row = $('table').find('tr#' + pid); var name = table_row.find('td:nth-child(1)').html(); table_ ...

Looping animations using AngularJS

I have implemented a custom directive to trigger an animation on an element when a specific field is empty on the page. However, I am facing an issue where the animation only works once when the user clicks the button with the directive. Subsequent clicks ...

Using Angular 6 to load external HTML files with CSS inside a router-outlet

I'm currently working on creating a json-based dynamic template using Angular 6. There are certain scenarios where I need to fetch external html content (which could be stored in a database) along with its corresponding css (also stored separately in ...

Issue with JQuery: object.id is returning as undefined even though it should have a value

While working with JQuery, I encountered a rather peculiar (or possibly foolish) error. The HTML code snippet in question is as follows: <input type="password" name="repeatPassword" id="id_repeatPassword" /> And within my javascript code, I have t ...

utilizing the angularjs $scope variable within a jquery bind method

I recently implemented the Fullcalender directive in my AngularJS application. While I was going through the documentation, I noticed that there is a double click handler available in the Fullcalender jQuery plugin. For reference: http://code.google.com/p ...

Determine the Height of the Container once the Font File has Finished Loading

When styling a website with a unique font using @font-face, the browser must download the font file before it can display the text correctly, similar to how it downloads CSS and JavaScript files. This poses an issue in Chrome (v16.0.912.63) and Safari (v5 ...

Having trouble accessing Firestore location and timestamp objects for Vuetify data tables

Unable to fetch Firestore document Geopoint (location) and Timestamp (date and time) objects in vue.js vuetify dataTables. Instead of displaying the actual location data (longitude:'' and latitude:'') in the table column, it shows [obje ...

How can NodeJS Websocket (ws) facilitate communication between various clients?

In my project, I have a scenario where client1 needs to share information with client2 and the latter should receive an alert upon receiving it. To achieve this, I am utilizing Websocket "ws" with NodeJS. The web page for client1 receives a response via A ...

How can I show the real width of an image on a mobile device?

I have integrated the infinite slide plugin from jQueryscript.net into my website. While it works perfectly on desktop with background images, I am facing an issue on mobile devices where the image width needs to be displayed in full. I attempted to adjust ...

Providing the module with the URL

How can I retrieve the URL within a module? module.exports = function(app, Reviews, Anon, User, url){ var url = url; console.log("url", url)// url is undefined how to get url function postHandler(req, res){ } app.post("/individual/"+ u ...