Is there a way to consolidate all Vue.js routes, templates, and components into a single file?

I am currently working on a Vue.js example where I aim to consolidate everything into a single file. My goal is to demonstrate the efficiency of using a small silo that can serve multiple routes. Here is what I have accomplished so far:

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index2</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.22/vue.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.2/vue-router.min.js"></script>
</head>
<body>
    <div class="container">
        <div id="app">
            <h1>Hello App!</h1>
            <p>
                <router-link to="/foo">Go to Foo</router-link>
                <router-link to="/categories">Categories</router-link>
            </p>

            <router-view></router-view>
        </div>
    </div>
<script>

    const Foo = { template: '#foo' }

    const Categories = {
        template: '#Categories',
        data: {
            categories: [{ title: "blah" }, {title:"yack"}]
        },
        methods: {
            saveNew: function(event) {
                alert("boo!");
            }
        }
    }

    const routes = [
        { path: '/foo', component: Foo },
        { path: '/Categories', component: Categories }
    ];

    const router = new VueRouter({
        routes: routes,
        mode: 'history',
        base: '/forums/admin/index2/'
    });

    const app = new Vue({
        router
    }).$mount('#app');

    Vue.config.devtools = true;

</script>

<template id="foo">
    <div>foo</div>
</template>

<template id="Categories">
    <div class="form-inline">
        <input type="text" name="newCategoryTitle" class="form-control" />
        <input type="button" v-on:click="saveNew" value="AddNew" class="btn btn-primary" />
    </div>
    <ul>
        <li v-for="category in categories">{{category.title}}</li>
    </ul>
    <table class="table">
        <tr v-for="category in categories">
            <td>{{category.title}}</td>
            <td><input type="button" value="Edit" class="btn btn-primary" /></td>
            <td><input type="button" value="Delete" class="btn btn-primary" /></td>
        </tr>
    </table>
</template>

</body>
</html>

https://jsfiddle.net/jeffyjonesx/sd79npwb/1/

My issue lies in the fact that the data within the Categories component does not properly bind to the template, especially when using a ul or table. Strangely enough, moving the ul to the beginning of the template causes it to break. However, the button handler on the loaded form functions correctly.

I believe I may be misunderstanding how to declare the templates, but I am unsure of the correct approach. Any guidance would be greatly appreciated.

Answer №1

Remember, templates in Vue can only have one root element. The first element Vue encounters is the div.form-inline, and everything else gets ignored. To avoid this, wrap your template in a single <main> tag (although using div works too, but for better semantics!).

<template id="Categories">
  <main>
    <div class="form-inline">
      <input type="text" name="newCategoryTitle" class="form-control" />
      <input type="button" v-on:click="saveNew" value="AddNew" class="btn btn-primary" />
    </div>
    <ul>
      <li v-for="category in categories">{{category.title}}</li>
    </ul>
    <table class="table">
      <tr v-for="category in categories">
        <td>{{category.title}}</td>
        <td><input type="button" value="Edit" class="btn btn-primary" /></td>
        <td><input type="button" value="Delete" class="btn btn-primary" /></td>
      </tr>
    </table>
  </main>
</template>

Another important point to remember is that during development, make sure to use the development version of Vue (vue.js) instead of the production version (vue.min.js) to receive warnings about issues like this.

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

What is the best way to add an array to my JSON object in Javascript?

I'm currently in the process of formatting an array into a JSON object for API submission. Struggling to find the right method to transform my array into the desired structure. This is what my array looks like: data: [ ["Lisa", "Heinz", "1993-04 ...

Using Vue JS to set a default value in a custom radio group

Recently, I attempted to implement a default value in a custom radio component that I developed. Below is the code snippet: <template> <div class="custom-radio-button"> {{value}} <div v-for= "item in localValue"> <input type ...

Utilizing jQuery's .clone() function to duplicate HTML forms with radio buttons will maintain the radio events specific to each cloned element

I'm currently developing front-end forms using Bootstrap, jQuery, HTML, and a Django backend. In one part of the form, users need to input "Software" information and then have the option to upload the software file or provide a URL link to their hoste ...

Tips for Ensuring Proper Functionality of the LIKE Button on Both Client and Server Sides

On my webpage, there is a 'LIKE' Button below each post. Clicking the 'LIKE' button triggers a GET request via AJAX to a like.php page that adds a row to a MySQL database table. Once the button has been clicked by a user, it disappears. ...

What is the most efficient way to manage form field errors using a single function in ReactJS?

I am facing a challenge with a form that requires users to answer three questions in order to register a new password. All fields must be filled out, and the user cannot submit the data to the server until all three questions are answered. My concern is h ...

Using a javascript component in vue.js with typescript - a step-by-step guide!

I have created a component in one project and now I want to make it accessible for use in another project. This is how I am currently exposing it: import ToastNotification from '../ToastNotification'; import Api from './api'; const Vu ...

Retrieve the ID of the nearest div without it being executed twice

I am currently working on implementing a close button using 'onclick' functionality. The goal is to hide the parent ID element when the user clicks the button, as shown below. function displayNone() { var id= $('.btnClose').closest ...

Enhancing my Javascript code by adjusting the styling of a link within the page navigation bar

Looking for assistance with a javascript and DOM code improvement. I currently have a page navigation bar structured like this (used on certain pages): <div id="pagebar"> <a href="iraq_pixra1.html">1</a> <a href="iraq_pixra2.html"> ...

How to extract a value from a BehaviorSubject within an Angular 6 guard

I have chosen this approach because I have another guard responsible for validating the user based on a token that was previously stored. This is how it was handled in previous versions of rxjs, but now with the latest version you can no longer use map on ...

Creating divs that adapt to different screen sizes without relying on flexbox

Currently, I am in the process of developing a chat interface where the viewport height is set to 100vh. The layout consists of a header/navbar, a "main content" section, and a footer housing the input field (you can view the code here) The way I have str ...

How to Set Up a Constant with ng-init Variables in AngularJs

Currently, I am utilizing AngularJs and setting up a variable in the ng-init within my model. <body ng-init="allowedState=2" ng-controller="amCtrl"> </body> My goal now is to create a constant based on this variable to be utilized across the ...

Include onload to element without running it in Puppeteer

I am currently developing a web scraping tool using Puppeteer. Once the webpage is fully loaded, I need to update the HTML code and include an onload event for certain elements. The issue is that in Puppeteer, the onload event is actually triggered automa ...

Is there a way to remove specific mesh elements from a scene in Unity?

When I create multiple mesh objects with the same name, I encounter difficulties in selecting and removing them all from the scene. Despite attempting to traverse the function, I have not been successful in addressing the issue. event.preventDefault(); ...

Guide on iterating through an array of objects a specified number of times to ensure it loops through all child arrays within the objects, if they exist

How can I iterate through an array of objects a certain number of times to access all the child arrays within each object and retrieve their IDs in order? let data = [{ "id": "1", "child": [ { "id": "12", "child": [ { ...

Before displaying the rows stored in the controller, ng-repeat initially displays one row

I am experiencing an issue with my back end service sending data to a $scope variable. I am using this variable to populate rows in a table with ng-repeat. Upon loading the page, initially one row is visible on the browser but then disappears once the loa ...

Exploring the world of threejs through the eyes of the protagonist

I have been working on creating an animation example using a GLTF file of Dragonball, where the user should feel like they are riding in a car from a first-person perspective. However, I am struggling to achieve this effect. Any tips on how I can make it h ...

Vue's keydown event will only fire when elements are in an active state

Encountering a strange issue while attempting to listen for keydown events in Vue.js. The keydown event is attached to a div tag that surrounds the entire visible area: <template> <div class="layout-wrapper" @keydown="handleKey ...

What could be causing the jQuery code to not function properly when the left or right keys are pressed during mousedown?

Explanation of HTML code: <div class="wrap"> </div> Description of JavaScript code: $(document).ready(function() { $("body").mousedown(function(event) { switch (event.which) { case 1: alert('hel ...

Using JavaScript promises to handle connection pooling and query execution

I am contemplating whether this approach is on the right track or if it requires further adjustments. Should I consider promisifying my custom MySQL getConnection method as well? request: function(queryRequest) { return new Promise(function(re ...

Sending a page identifier through a menu

Being new to vue/nuxt, I encountered an issue when setting up the frontend for a headless CMS. I have defined two routes as follows: Pages -StandardPage ->_standardPage.vue -InfoPage ->_InfoPage.vue Both my _standardPage.vue and _infoPage.v ...