Encountering an error while attempting to add a new component instance in Vue through a button click

Just to start, I want to mention that there might be a more appropriate way to achieve what I'm trying to do. Essentially, I'm looking to dynamically add an instance of a Vue component when a user clicks a button to expand it. I came across this discussion on the vue.js forum for guidance. However, I'm encountering an issue where triggering the insert function through a button click isn't working as expected. The console error indicates "addNewStop is not defined at HTMLButtonElement.onclick".

The HTML structure in my template:

<div id="newCont"></div>
            <button type="button" class="btn-primary" id="addStop" onclick="addNewStop()">Add Stop</button>

The script being called:

  import Stops from '@/components/Stops'

  const ComponentCtor = Vue.extend(Stops)
  const componentInstance = new ComponentCtor({})
  function addNewStop() {
    componentInstance.$mount('#newCont')
  }

I readily admit that I wasn't entirely sure about the correct approach initially and have found limited information on inserting new component instances. If there are alternative or better options out there that I should explore, I would appreciate any suggestions!

Edit:

The 'Stops' template actually consists of form inputs allowing users to specify delivery stops along a truck route. Below is its template structure:

<template>
  <div class="stops">
    <h4>Delivery</h4>
            // Form fields for shipper name, location, date, time, etc.
            
  </div>

</template>

Answer №1

When you find yourself directly manipulating the DOM, such as adding a component, while using Vue.js, it's usually a sign that you're not leveraging Vue's data-driven approach as intended. Vue is designed to handle data updates, leaving the DOM manipulation to the framework itself. Although your question lacks specific details for a tailored solution, there are some general strategies that may be effective.

If you have multiple instances of the Stop component in the DOM and each button click adds another instance, utilizing v-for to render the stops from data and having the button click handler add an entry to the data array could be a suitable approach.

<template>
    <form>
        <fieldset v-for="(stop, index) in stops" :key="index">
            <stop v-bind="whatever"/>
        </fieldset>
        <button @click="onClick">Add one</button>
    </form>
</template>

<script>
export default {
    data() {
        return {
            stops: []
        };
    },
    methods: {
        onClick() {
            this.stops.push(/* whatever */)'
        }
    },
    components {
        Stop
    }
};
</script>

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

Are there benefits to using AngularJS for a basic AJAX site?

After creating a basic website, I have decided to enhance it with a JavaScript overlay for various functionalities such as: Implementing ajax in the search box and pagination for seamless loading of results without refreshing the page Integrating the HTM ...

Transferring information stored in a SQLite database using Python and displaying it in the

I am looking for a way to display data from an sqlite3 database in the front-end of my application when a GET request is made. Currently, I have managed to render the data as a JSON dump using the following code snippet: if self.path == "/stuff" : ...

Create a customized menu with jQuery that disappears when hovered over

Check out this menu I've created: http://jsbin.com/useqa4/3 The hover effect seems to be working fine, but I'm looking to hide the div #submenuSolutions when the user's cursor is not on the "Solution" item or the submenu. Is there a way to ...

Combining two arrays filled with objects to form a collection of Objects on a Map

In my JavaScript code, I'm receiving data from a WebService that looks like this: { "fire": { "totalOccurence": 2, "statsByCustomer": [ { "idCustomer": 1, "occurence": 1 }, { "idCustomer": 2, ...

What could be the reason for my CORS headers not aligning even though they appear to be identical?

I encountered an issue while using passport js with REACT. When trying to fetch the logged in user data, I faced a problem where the cors header of fetch didn't match even though they are identical. Here is the endpoint I am sending the fetch request ...

As the background image shifts, it gradually grows in size

I'm attempting to create an interesting visual effect where a background image moves horizontally and loops seamlessly, creating the illusion of an infinite loop of images. Using only HTML and CSS, I've run into an issue where the background ima ...

Retrieving Records within a Specific Date Range for Check-ins and Check-outs

Our team is currently working on developing booking software that requires handling different room pricing based on specific dates. Each room has distinct pricing for weekdays and weekends. ROOM 1 Pricing 1: September 1st - November 3rd, Weekday: $100, W ...

Tips for connecting to multiple items in an md-select element from within a directive

Looking to develop a straightforward directive that displays either a textbox or dropdown based on whether an array is provided for the model property on the scope. Any value other than explicitly setting false in the directive markup such as multiple="fa ...

Execute a particular NodeJS function within the package.json scripts section

I've got a NodeJS file with an export function that looks something like this: test.js exports.run = function(){ console.log('You execute this function!'); }; Is there a way to trigger this function specifically by using a custom comman ...

How to trigger an Angular (ionic) view update following an HTTP post request

Is there a way to update the expression in my view after making an HTTP post request? I have tried using the $scope.$apply function, but it gives me an error from ionic.bundle.js saying "$digest already in progress". Could this be a mistake on my part or ...

React's onClick event listener is malfunctioning

My code is malfunctioning and the reason behind it remains unclear to me... const MenuPage = () => { const [title, setTitle] = useState(""); function handleClick(e){ e.preventDefault(); setTitle(e.currentTarget.childNo ...

Dynamic header that adjusts to fit window size fluctuations

I'm currently working on a website and trying to make it responsive by adjusting to changes in the browser window size. I'm having trouble changing the header height based on the window size unlike how it works for my pictures in CSS: #l ...

Creating interactive buttons on the fly in Angular

In my Angular application, I am attempting to create a button dynamically that calls the deleteRow() function and passes a username parameter upon click. Despite successfully passing the username to the controller, the generated button ends up passing unde ...

Sending a multi-level property object to the controller in a post request

I am facing a challenge where I need to transfer an object from the view to the controller, and the model comprises a list of objects, each containing another list of complex objects. Let's consider the following models: public class CourseVm { p ...

What is the process for implementing a fallback image in Material UI?

Hey there! I'm currently looking to customize the fallback image of a Material UI Avatar with my own original image. Does anyone have any tips on how I can achieve this? const fallbackImage = "../../fallback/img.png" const AvatarWithBadge = ...

Send JSON data from a .json file to a Vue component via Express, then store it in a variable

How can I display data on my webpage that is stored in a dsa.json file? My setup involves using express with vue. Below is the code snippet from server.js: var data; fs.readFile('./dsa.json', 'utf8', (err, data) => { if (err) th ...

How to retrieve multiple person or group values in SharePoint using JavaScript

Names from my SharePoint list are stored with the field names 'People' and 'Responsible', added using a peoplepicker. These fields are of type 'person or group' in SharePoint. In my Service file, I have the following code: ...

How can I resolve the issue of encountering the "Modal dialog present: If you navigate away from this page, any unsaved changes will be lost" message while using Internet Explorer with

Here's the code snippet I'm working with. While it successfully removes the alert box, it throws an error in the console: Exception in thread "main" org.openqa.selenium.UnhandledAlertException: Modal dialog present: If you leave this page, any c ...

What is the most efficient way to transfer an object between two functions in AngularJS?

As a beginner in AngularJS and Javascript, I recently attempted to pass an object from one function to another. Here is the HTML Code: <div ng-click="getValueFromHtml(userObj)">send Object </div> This is the Controller Code: $scope.getValueFr ...

Is the functioning of closures identical when applied to class methods?

Recently, I started learning React.js (along with Javascript) and I have a basic question to ask. I have created a small component that consists of 3 buttons. Each time these buttons are clicked, the value increments by one. Here is a working example: cl ...