Generate a duplicate of the entire div using Vue when it is clicked

I've been grappling with this issue and haven't found a straightforward solution yet. My goal is simple: I want to click on the 'Add another zone' link and, upon clicking it, recreate the entire div with ID "vueAC" below the current one.

How can I achieve this considering my existing structure:

    <div id="vueAC" class="uk-grid">
    <div class="uk-width-2-10"  >
        <input size="4" type="text" name="mapNumber">
    </div>
    <div class="uk-width-6-10">
      <input style="width:100%" type="text" placeholder="what are you looking for?" v-model="searchString" v-on:keyup="autoComplete" class="form-control">
      <div class="panel-footer componentList" v-if="results.length">
       <ul class="list-group">
        <li class="list-group-item" v-for="result in results">
           <a v-on:click="saveAttribute(result)">@{{ result.attribute_value }}</a>
        </li>
       </ul>
      </div>
    </div>
    <div class="uk-width-2-10" style="border: 1px solid black; height:50px; width: 50px; margin: 0 auto;" >
    
    </div>
</div>

<div>
    <a v-on:click="addDiv">Add another zone</a>
</div>

new Vue({
  components: {
  },
  el: "#vueAC",
  data(){
   return {
    searchString: '',
    results: []
   }
  },
  methods: {
   autoComplete(){
    this.results = [];
    console.log(this.searchString);
    if(this.searchString.length > 2){
     axios.get('/search',{params: {searchString: this.searchString}}).then(response => {
      this.results = response.data;
      console.log(this.results);
      console.log(this.searchString);
     });
    }
   },

   addDiv(){
    // My objective here is to reproduce the entire div with ID vueAC just below the current one
   }
  }
})

Answer №1

If you want to ensure the div gets re-rendered, consider adding a key attribute to the vueAC div and updating the key when needed:

<div id="vueAC" class="uk-grid" :key="myKey">
</div>

By using a number as the key and incrementing it, you can easily trigger a re-render:

new Vue({
data(){
 return {
   myKey: 0,
 }
},
methods: {
 addDiv(){
   // Implement required logic here.

   this.myKey++;
 }
}
})

For more details, refer to the documentation: https://v2.vuejs.org/v2/api/#key

Answer №2

addDiv function must be defined outside the component as a parent component method. Within the parent component, an array of zones should be included in the data property. When addDiv is clicked, add a new empty zone with no information to this.zones. Use v-for directive to iterate over each zone.

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

An issue with Ajax's syntax

Help needed with my ajax code. I'm encountering an error while trying to send data in Ajax - specifically with the data syntax. Despite several attempts, I have not been able to successfully resolve this issue. Here is the portion of code causing tro ...

You will still find the information added with JQuery append() even after performing a hard refresh

After making an Ajax call using JQuery and appending the returned information to a div with div.append(), I encountered a strange issue. Despite trying multiple hard refreshes in various browsers, the appended information from the previous call remained vi ...

Accessing the ID of individually selected rows as well as multiple rows in Vuetify data tables by utilizing the "show select" property

In order to delete specific records from the tables based on user selection, there needs to be functionality implemented where if a user selects any 3 options, a delete button will appear. This delete button should allow for the deletion of those specifi ...

Guide on extracting part of a string in JavaScript from a specific starting point to a designated character

Currently working on a JavaScript project where I am in need of extracting words enclosed within two brackets. For example: [Green]- Amazon I specifically require the word "Green" from within the brackets. Using indexOf() won't work as there could ...

Is there a way to retrieve the value of a round slider using jQuery?

After creating a round slider using resources from various websites, I encountered an issue. I am trying to retrieve the current value of the slider and store it in a database, but I am facing difficulties in doing so. Although the slider displays the va ...

What is the best way to access the camera of a mobile phone through a web application?

Whenever I try to access the camera on my mobile device through a web app, I encounter an issue. While the camera works perfectly fine on the web version, it fails to show up on my mobile device unless I add https:// in the URL. How can I resolve this prob ...

Utilizing React to adapt to varying HTML layouts while maintaining consistent component usage

How can I create an App with two different views for mobile and desktop without relying solely on CSS Media Queries? I have been searching for guidance but so far haven't found a solution. Any advice or direction on where to find documentation or oth ...

Unable to retrieve data from a nested object within a JSON structure

In my React project, I have created a function component like the one below: function FetchData() { const [randomUserData, setRandomUserData] = useState(''); const url = 'https://randomuser.me/api/'; const fetchData = () => { ...

Are you experiencing issues with downloaded files appearing corrupted when transferring them from an expressJS (sendFile) server to VueJS?

I have a backend API built with expressjs that is able to send files when provided with a fileID. Everything seems to be working correctly on the backend, as when I directly type the route URL into my browser (e.g. http://localhost:8080/download?id=1234), ...

What is the best way to organize data for creating line plots using vue/chart.js?

I am working on retrieving data from an API and using vue-chartjs to generate a line plot. But, I'm facing an issue where only the first two points are being plotted. It seems like my data structure might be incorrect, but I'm struggling to figu ...

Having trouble with the password strength indicator in React-redux?

Hey there, I'm currently working on implementing a progress strength bar for password validation in React. While I've made progress with the code to check the password regex, I'm struggling to understand how to incorporate the password stren ...

Tips on establishing validators for deeply nested form controls within form groups in Angular 6 reactive forms

In my form array (experiencesArray), I have nested nested nested form controls (companyname), as shown below. this.personalFormGroup = this._formBuilder.group({ professionalInfo: this._formBuilder.group({ totalexpyears: ['', Validators.req ...

We have successfully integrated the Wijemo event calendar with our Angular controller

I've been attempting to connect the wijeval to an array of events within an AngularJS Controller. Here's what I've attempted so far: View: <div ng-app="MyApp" ng-controller="MainController"> <wijevcal viewtype="week" eventsdat ...

Implement a jQuery loading animation triggered by scrolling down the page

Can anyone offer guidance on how to trigger an animation as you scroll down a webpage? I've come across this feature while browsing through this website: I would love to include code examples, but I'm unsure of where to start with implementing t ...

IE Troubles: Timer Function Fails in Asp.Net MVC

I implemented the following code snippet: @Using Ajax.BeginForm("Index", New AjaxOptions() With { _ .UpdateTargetId = "AnswerSN", .HttpMethod = ...

How can you show a top-level component across various routed pages in Nuxt without having to reload it each time?

Recently starting a new job, I have been tasked with creating a website using nuxt. In a typical nuxt layout file, the structure would look something like this: <NavMenu /> <Nuxt /> - various routed pages <Footer /> When transitioning be ...

Checking conditions sequentially in Angular

I have a unique use case that requires me to verify certain conditions. If one condition fails, I should not proceed to the next one. Instead, based on the failed condition, I need to display a dialog with a title and description explaining what went wrong ...

Concealing the div during the initial page load

person.jsp <script type="text/javascript"> function validateadvance() { document.getElementById("fn").style.visibility = "visible"; } $(function() { $(".dp").datepicker(); }); </s ...

Is there a way to limit the width of the input box once it reaches a specific pixel measurement?

One issue I'm facing involves the following code snippet: <html> <head> <script type="text/javascript"> function Expand(obj){ if (!obj.savesize) obj.savesize=obj.size; obj.size=Math.max(obj.savesize,obj.v ...

Steps for updating a text section beneath a carousel

I'm looking to enhance my webpage with a bootstrap carousel, which is pretty standard. However, I want the content under each slide to change dynamically, but I'm struggling to make it work. As a newbie, I could use some guidance. I've atte ...