Vue-Routes is experiencing issues due to a template within one of the routes referencing the same ID

I encountered an issue while developing a Vue application with Vue-routes. One of the routes contains a function designed to modify the background colors of two divs based on the values entered in the respective input fields. However, I am facing two problems. Firstly, the router stopped functioning after implementing this color changing feature. Secondly, the actual color change is not taking place as expected, leading to a double failure situation. Upon inspecting the console in Google Chrome, I came across the following message: "vue.js:597 [Vue warn]: Cannot find element: #container".

It seems evident that these issues are interconnected. The real question now is how do I go about resolving them?

HTML

<div id="container" v-bind:style="bga">
   <div class="top" v-bind:style="bgb">
      <div id="app">
         <h1 id="vueHead">Vue routing</h1>
         <h2 class="menu">
            <router-link to="/">Color</router-link>
            <router-link to="/main">Main</router-link>
         </h2>
      </div>
   </div>
   <!-- component matched by the route will render here -->
   <router-view></router-view>
</div>

index.js (routes)

import MainPage from '../components/mainPage.js'
import ColorPage from '../components/colorPage.js'

var urlend;

const routes = [
    {path: '/', component: ColorPage},
    {path: '/main', component: MainPage},
    ];
const router = new VueRouter({
    routes // short for `routes: routes`
});
var vm = new Vue({
    el: '#container',
    router
});

colorpage.js

const ColorPage = {
    template: `
<div id="middle">
    <label id="colorLabel"><h2> {{ info }} </h2></label>
    </br>
    <input type="text" class="colorInput" v-on:input="bga.backgroundColor = $event.target.value" placeholder="here...">
    </br>
    <input type="text" class="colorInput"  v-on:input="bgb.backgroundColor = $event.target.value" placeholder="... and here!">
</div>
`
};
var color = new Vue({
    el: '#container',
    data: {
        info: 'Change Colors By Typing Their Names:',
        bga: {
            backgroundColor: ''
        },
        bgb: {
            backgroundColor: ''
        }
    }
});

export default ColorPage

Answer №1

Within your colorpage.js file, there is a new Vue() being initiated to create a fresh instance of Vue. To achieve what you're aiming for, it may be more appropriate to develop a new component.

When working with components, you do not have to specify where they will be mounted using el; instead, the responsibility lies with Vue router. Within your Vue application, el should only be defined once for the Vue instance to mount itself. Once the Vue instance has been successfully mounted, routing takes place internally within Vue.

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 exporting a React Component without using ownProps in a redux setup with TypeScript

I'm currently working on a project using typescript with react-redux. In one of my components, I am not receiving any "OwnProp" from the parent component but instead, I need to access a prop from the redux state. The Parent Component is throwing an er ...

Encountering a 404 error while using Angular HTML5Mode setting

I recently enabled pretty URLs in my Angular application by switching to html5mode. However, whenever I try to refresh the page, I encounter a 404 error. For instance, if I access my app through , everything functions as expected. But when I attempt to r ...

Timezones not synchronizing properly with Moment.js

Hello everyone, I am currently exploring the world of moment.js along with the timezone add-on. I'm encountering some issues with a world clock project that involves using moment.js and moment-timezone.js together on a page where highcharts are also p ...

Tips for creating a hierarchical multilevel datatable with JavaScript

I am currently working on implementing a multi-level datatable without relying on any external plugins or libraries. My goal is to achieve this using pure JavaScript, JQuery, or AngularJS. I have explored the following resources: Traverse all the Nodes of ...

Is there a method for configuring NextAuth to utilize the /src/app directory instead?

Is there a specific method to instruct NextAuth to redirect to this particular directory, but within the src/app directory? All of my routes are now located there due to the changes in Next.js 13. Below is an example of the code I am using: export const a ...

Error: An issue occurred in the driver.execute_script function causing a JavascriptException. The error message indicates

When attempting to run some JavaScript code on the Chrome driver, I encountered a JavascriptException. Despite my confidence in the correctness of the JS code, the following error message was displayed: raise exception_class(message, screen, stacktrace) s ...

Choosing all components except for one and its descendants

I am searching for a method to choose all elements except for one specific element and its descendant, which may contain various levels of children/grandchildren or more. What I'm trying to accomplish is something like... $("*").not(".foo, .foo *").b ...

The issue arises when d3.scaleLinear returns NaN upon the second invocation

My journey with d3.js is just beginning and I'm taking it slow. Currently, I'm focused on creating a bar chart where data is loaded from a json file. When I click on the bars, the data changes to another column in the json. This is how my json f ...

Using recursive setTimeout in Javascript may not always utilize the entire final JSON object that is returned

My current approach involves making recursive calls to a URL until it returns either a success or reaches the maximum limit of tries. Below is a compact version of the relevant code: function doSomething(numRetries) { $.post('someURL', {retr ...

Python script for extracting content from web pages that are loaded dynamically

I am facing an issue with extracting content from a webpage on my website. Despite trying to use selenium and clicking buttons, I have not been successful. #!/usr/bin/env python from contextlib import closing from selenium.webdriver import Firefox import ...

VS Code sees JavaScript files as if they were Typescript

I have recently delved into the world of Typescript and have been using it for a few days now. Everything seems to be working smoothly - Emmet, linting, etc. However, I've encountered an issue when trying to open my older JavaScript projects in VS Cod ...

Testing a function in Jest that utilizes the current date

I have a function that checks if the parameter date is the same as or later than today. In my function, I am using new Date() like this: import moment from "moment"; const validateDate = ({ date }) => { return moment(date, "DD-MM-YYYY").isSameOrAfte ...

Is there a way for me to produce a random choice depending on the option selected by the user in the <select> menu?

As a beginner in JavaScript, I am attempting to create a feature where users can select a genre from a dropdown list and receive a random recommendation from that genre displayed on the screen. In essence, my goal is to allow users to get a random suggest ...

Transferring a dynamic HTML file created using R's animation package onto a WordPress platform

After using the animation package in R to create an HTML file, I'm facing some challenges uploading it to my WordPress blog. It appears that additional js or css files may be required for proper functionality, but I'm uncertain about the process. ...

The AngularJS 2 TypeScript application has been permanently relocated

https://i.stack.imgur.com/I3RVr.png Every time I attempt to launch my application, it throws multiple errors: The first error message reads as follows: SyntaxError: class is a reserved identifier in the class thumbnail Here's the snippet of code ...

Validation of md-datepicker and md-select in Angular MaterialAnguar Material validation

I am working on a form that includes input fields, datepickers, and dropdowns. Currently, if the required input fields are left blank upon submission, they are highlighted with a red line. However, I want the datepickers and dropdowns to also be highlighte ...

Highlight all text in the textbox upon selection

I discovered a helpful script on how to select all contents of a textbox when it receives focus using JavaScript or jQuery. My attempt to implement this in IE10 revealed that the focus was being cleared at a later time, and my efforts to prevent this (whi ...

Node.js allows for keeping pipe and sockets open even after streaming an HTTP response

My current challenge involves streaming data from an HTTP response to a cloud storage provider within an internal service. const response = await request<Readable>({ headers: httpOpts?.headers, data: httpOpts?.data, url, method, responseTyp ...

spring fails to run javascript

In my project, I am utilizing Spring MVC 3 framework. Below is the snippet of my AddressController: @Controller public class AddressController { private static Logger logger = Logger.getLogger(AddressController.class); @RequestMapping(value="/ad ...

Error encountered: Jquery - function is not defined

Currently, I am developing a widget that is integrated into a client's website and it loads a jQuery file. However, we need to check if jQuery is already loaded on the client's page to prevent any conflicts, in which case we would not load our ow ...