Utilizing custom emitted events as props for a newly created component within VueJs

My application comprises of:

A component called

<consl :output="output" @submit-to-vue><consl>

that includes an input triggering a submit() method when the enter key is pressed.

<div> 
    <output v-html="output"></output>
    <div id="input-line" class="input-line">
        <div class="prompt">{{ prompt }}</div>
        <div>
        <input class="cmdline" autofocus 
            v-model.trim="command" 
            @keyup.enter="submit"  
            :readonly="submited" />
        </div>
    </div>

The submit() method then triggers an @submit-to-vue event to the parent method submitv() which creates an instance of the same component and adds it to the DOM.

//........
methods: {
    submit: function () {
        this.$emit('submit-to-vue')
        this.submited = true
    }
},

and

//......
methods: {
    submitv: function () {
        var ComponentClass = Vue.extend(consl)
        var instance = new ComponentClass({
            propsData: { output: this.output }
        })
        instance.$mount() // pass nothing
        this.$refs.container.appendChild(instance.$el)

What I aim to achieve?

I intend to generate a new consl component and append it to the DOM each time the previous one is submitted. (To simulate a terminal in my app)

The issue

Upon submission, the newly created component lacks the @submit-to-vue event listener, making it unable to call the submitv() method.

Queries

  • How can I troubleshoot this problem?
  • Is this approach suitable for VueJs or is there a more sophisticated method available?

Answer №1

Define a data property called 'childs' in the parent component to store all the child components that have been created.

When the parent component receives the event 'submit-to-vue', add a new child component to 'this.childs'.

Use 'v-for' to render these child components.

Remember: always follow a data-driven approach and avoid direct manipulation of the DOM as much as possible.

Below is a simple demonstration:

Vue.config.productionTip = false

Vue.component('child', {

  template: `
  <div> 
    <div>Label:<span>{{output}}</span></div>
    <div>Value:<span>{{command}}</span></div>
    <div id="input-line" class="input-line">
        <div class="prompt">{{ prompt }}</div>
        <div>
        <input class="cmdline" autofocus 
            v-model.trim="command" 
            @keyup.enter="submit"  
            :readonly="submitted" />
        </div>
    </div>
  </div>`,
  props: ['output'],
  data() {
    return {
      submitted: false,
      command: ''
    }
  },
  computed: {
    prompt: function () {
      return this.submitted ? 'Already submitted, input is read-only now' : ''
    }
  },
  methods: {
    submit: function () {
      this.$emit('submit-to-vue')
      this.submitted = true
    }
  }
})

app = new Vue({
  el: "#app",
  data: {
    childs: [{'output':'default:'}]
  },
  methods: {
    addChild: function () {
      this.childs.push({'output': this.childs.length})
    }
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
  <div>
    <ul>
      <li v-for="(child, index) in childs" :key="index">
        <child :output="child.output" @submit-to-vue="addChild()"></child>
      </li>
    </ul>
  </div>
</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

Jquery button click event is malfunctioning after the inclusion of jquery keyboard plugin

When I try to gather user input from a textbox using jQuery keyboard.js, the functionality works perfectly fine if I exclude the virtual keyboard code. For more information on keyboard.js, you can visit: https://github.com/Mottie/Keyboard/wiki Below is t ...

Sometimes the data-autoplay feature does not function properly in jQueryfullPage.js

I am in the process of developing an HTML page using jQueryfullPage.js. Within this page, I have incorporated 17 videos across 17 different sections. These videos are presented as YouTube iframes with a data-autoplay attribute. Overall, everything is fun ...

What advantages do interfaces as data types offer in Angular compared to using classes?

After watching a tutorial from my teacher, he showed us this code snippet: https://i.sstatic.net/MA3Z9.png He mentioned that the products array, defined as type any [], is not taking advantage of TypeScript's strongly typing. He suggested using an I ...

Using 'cy.get' to locate elements in Cypress tutorial

Is there a way to search for one element, and if it's not found, search for another element? cy.get(@firstElement).or(@secondElement).click() Can I use a function similar to || in conditions for this scenario? ...

Is Vue.js rendering jQuery obsolete?

Is it true that utilizing vue js will render the jQuery library unnecessary for experienced developers? I would appreciate any insight on this matter. ...

CodeIgniter session not being updated after AJAX call

What could be the reason for CodeIgniter session not updating values after an AJAX request? Controller index: public function index() { $this->session->set_userdata( 'greetings', 'hello!' ); } AJAX request: $.ajax({ ty ...

Determine whether the request was made using ajax or traditional non-ajax methods

While testing the PHP code below, I noticed that the headers in the request do not indicate that it is JavaScript sending the request instead of a non-JavaScript user: Accept:*/* Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8 AlexaToolba ...

Error occurred while attempting to upload a file using multipart form data: TypeError message displayed - Unable to access properties of undefined (specifically '0')

I am encountering an issue while trying to send multipart/form-data using axios from the frontend. The same post request works fine in Postman/Insomnia but fails when executed from the frontend. The backend shows the following error: node:events:505 ...

Creating a custom backdrop for your kaboom.js webpage

I created a kaboom.js application and I'm having trouble setting a background for it. I've searched online extensively and attempted different methods on my own, but nothing seems to be working. (StackOverflow flagged my post as mostly code so I ...

Ways for enabling the user to choose the layout option

I am looking to develop a customized reporting system where users can select the specific fields they want to include in the report as well as arrange the layout of these fields. The data for the reports is sourced from a CSV file with numerous columns. Us ...

What is the process for determining the total of elements within an array?

Imagine you have the following array: const items = [ { "amount1": "100", "amount2": "50", "name": "ruud" }, { "amount1": "40", "amount2": "60", "name": "ted" } ] Your goal is to calculate the sum of all amount1 and amount ...

Having some success with AngularJs autocomplete feature

Currently working on a small search application that utilizes Elasticsearch and AngularJS. I have made progress in implementing autocomplete functionality using the AngularJS Bootstrap typeahead feature. However, I am encountering difficulties in displayin ...

The ReCaptcha and AJAX Integration

I am attempting to display the ReCaptcha image using its AJAX API. I have been following the instructions from this documentation and observing the behavior of this demo. Despite my efforts, I am still unable to create a functional fiddle. I have added jsf ...

Changing the border color of a Material UI textbox is overriding the default style

Upon the initial page load, I expected the border color of the text box to be red. However, it appeared grey instead. I tried setting the border color to red for all classes but the issue persisted. Even after making changes, the border color remained unch ...

Why aren't Material UI v5 styles being applied to the class?

I have been attempting to customize the MUI slider by applying styles using the className prop. However, I am facing an issue where the styles assigned to the main class are not being applied, but other styles such as the 'hover' state are workin ...

A guide on integrating functions into dynamically created buttons using the DOM

Is there a way to add functionality to the button labeled "CLICK ME TO EDIT"? I'm looking for some ideas on how to do this. var comment = prompt("Type content for new paragraph here", ""); var newParagraph = document.createElement('p'); new ...

Utilizing React and Material-UI to Enhance Badge Functionality

I am exploring ways to display a badge icon when a component has attached notes. I have experimented with three different methods and interestingly, the results are consistent across all of them. Which approach do you think is the most efficient for achiev ...

Discover how to implement custom data filtering in an Angular controller

Help needed: How can I remove decimals, add $ symbol in an Angular controller? Any ideas? $scope.data = [{ "key": " Logo", "color": "#004400", "values": [ [0, parseInt($scope.myappslogo)] ] }, { "k ...

xhttp.load path for server-side module

I'm currently working on developing a node package and in my JavaScript code, I have the following: const calcHtml = './calc.html'; const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4) { ...

The Bootstrap modal stubbornly refuses to close even after resetting the HTML body

I am having an issue with my bootstrap modal where the closeModal button is not functioning properly after the printModal button has been clicked. The modal does not close as expected. Step 1: Click on the printModal button after the modal pops up (this w ...