A guide on implementing Vue data binding on elements that have been dynamically generated

Within my code, I am dynamically creating numerous elements on the server side. I store the HTML of these elements in a JavaScript object, remove them, and then conditionally add them to various parts of the page.

There is one specific element for which I desire data binding so that I can reference that binding in a v-if directive. However, when I add the v-bind on the server side, it gets lost after I copy the HTML.

Since I am only adding the elements in my JavaScript code, I am unable to register the v-bind in my template. Additionally, providing the content in a component is not an option since it is dynamic and relies on input from the server.

How can I properly register the binding?

Here is some sample code:

Dynamically generated form elements (server side):

<div id="archive" style="display: none;">
   <div><input type="text" name="purpose" v-bind:value="purpose" id="id_purpose"></div> <!-- v-bind has no effect -->
   <div><input type="text" name="purpose__iexact" id="id_purpose__iexact"></div>
   <div><input type="text" name="purpose__contains" id="id_purpose__contains"></div>
   <div><input type="text" name="purpose__icontains" id="id_purpose__icontains"></div>
   <div><input type="text" name="purpose__in" id="id_purpose__in"></div>
   ...
</div>

Script to copy the HTML:

    var input = {};
    var archive = document.getElementById('archive');
    for(var i = 0; i < archive.children.length; i++) {
        var div = archive.children[i];
        input[div.firstChild.name] = div.innerHTML
    }
    archive.parentNode.removeChild(archive);

Template code to display a certain input field dynamically (client side):

<div class="inline" v-html="input[SOME CONDITIONAL COMPUTATIONS]"></div>

Answer №1

Here is the recommended approach for rendering a vue scene:

    <template>
  <div>
    <input type="button" value="Add new item" @click="addItem">
    <hr>
    <div v-for="(item,index) in data" :key="index">
      <span v-html="item.html"></span>
      <h3>Model data {{item.model}}</h3>
      <input type="text" v-model="item.model">
      <input type="button" value="Click me" @click="item.action(index)">
      <input v-if="item.show" type="button" value="Remove me" @click="removeItem(index)">
      </br>
    </div>
  </div>
</template>

<script>

export default {

  data() {
    return {
      item: {
        model: "",
        show:true,
        html: "<b>mydata html</b>",
        action: function(index) {
          console.log(`Clicked ${index} element.`);
        }
      },
      data: [
        {
          model: "",
          show:false,
          html: "<b>mydata html</b>",
          action: function(index) {
            alert(`Clicked ${index} element.`);
            console.log(`Clicked ${index} element.`);
          }
        },
        {
          model: "",
          show:true,
          html: "<b>mydata html</b>",
          action: function(index) {
             alert(`Clicked ${index} element.`);
            console.log(`Clicked ${index} element.`);
          }
        }
      ]
    };
  },
  methods: {
    addItem() {
      let item = Object.assign({}, this.item); // another way to duplicate Observer
      this.data.push(item);
    },
    removeItem(index){
      this.data.splice(index,1)
    }
  }
};
</script>

You can introduce a show boolean property to the item object and use the v-if="" attribute on the div to hide it. I trust that this example will be of assistance to you.

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

To toggle between two scope variables within a view when one is not defined

In my application, I am utilizing two scope variables: $scope.banner and $scope.defaultBanner. The banner is fetched using a service, but in cases where the banner file does not exist, the variable will be empty as the service returns nothing. My goal is ...

Utilize an API call to fetch data and seamlessly showcase it on the webpage using Vue.js

I have created an API and defined it in my TypeScript file const Book = { async getBookType(intID: string): Promise<Book[]> { // const intId = API.Product.getCurrentId(); const intId = ''; const response = await h ...

Leveraging the power of THREE.js TransformControls

I am currently working on a project in JSBin and attempting to incorporate the THREE TransformControls class. Due to constraints, I am unable to share my full code, but my JavaScript is contained within <script type="text/javascript"></s ...

JQuery failing to trigger AJAX function

I'm struggling with what seems like a simple issue and it's driving me crazy. The problem lies in this straightforward section of the website. I have a .js file that uses ajax to save a post into the database when the submit button is clicked. A ...

Conceal CSS navigation bar with a single click

Is there a way to hide the dropdown menu after clicking on any item? How can I make it return to its initial state? Primarily, I want it hidden for mobile users. It currently works fine but remains open on mobile devices until another part of the page is c ...

Discover the secrets of flying to customized coordinates stored in variables using Leaflet.js

I'm currently working on a fire location tracking website and I'm facing an issue with leaflet.js. As a newcomer to Leaflet, any assistance would be greatly appreciated! I have a script that successfully retrieves the id of a specific row from a ...

A step-by-step guide on incorporating HTML into a div element with jQuery

<div class="segment"> <div class="segment-inner"> <p>Content Goes Here...</p> </div> </div> <script type="text/javascript"> jQuery(document).ready(function () { jQuery('<i class="fa f ...

Effortlessly add the input form using the selectpicker feature

Is it possible to automatically input values using selectpicker and calculate a form without having to manually click on the input field first? The JavaScript for calculating is working, but I need the Input Price to have a value automatically when selecti ...

Difficulty in simultaneously sending POST and GET requests - Nuxt 3

Currently, I am attempting to retrieve the last projects of a user from the database by providing their name and fetching all the latest projects associated with that user. Unfortunately, every time I attempt this, I encounter an error message stating, "Un ...

The Cube Render in Three.js fails to show any output

I'm having trouble rendering a cube using Three.js. I followed the tutorial on tutorialspoint exactly, but all I see is a blank screen. Even though I tried rendering the code, I can't seem to get anything to display on the screen. The code looks ...

Error message on TSC Printer: ActiveXObject is not defined in Chrome

I encountered an error in Chrome saying "Uncaught ReferenceError: ActiveXObject is not defined." Here is my code: let TSCObj TSCObj = new ActiveXObject("TSCActiveX.TSCLIB") TSCObj.ActiveXopenport("TSC Alpha-2R") TSCObj.ActiveXsendcommand("SIZE 50 mm, 50 ...

Angular's routeProvider is failing to load the next template

I am struggling to implement a feature where each item in a list has a button that, when clicked, uses $routeProvider to navigate to a specific template. However, I keep encountering 404 errors when trying to access the page through the link. Any guidance ...

Is there a way to retrieve the Response object in Express from outside the Route

Currently, my backend API is built using Express JS. Instead of using the res object directly in the route controller, I am looking to access it from a custom service. While I know that I can simply pass res as an argument to the service function and use ...

SCRIPT438: The operation failed because the object does not have the ability to use the 'forEach' property or method

Issue with IE8: Property or method 'forEach' not supported $('.tabs').tabs(); $('#search-consumables [data-ajax-call]').change(function() { var $this = $(this), settings = $this.data(), $target = $(setti ...

What could be causing the npm install command to not save packages in the /node_modules directory?

After running npm install to add a package, npm indicates that the installation was successful. However, upon checking the node_modules folder, I'm unable to locate the installed package. In order to access the package, I have resorted to using npm in ...

Experiment with jQuery and JavaScript compatibility specifically on Internet Explorer 6

Seeking advice on the most effective method to test my web app using IE6. I currently have IE8 installed on my computer, and am considering utilizing a Virtual Machine. Are there any other alternatives worth exploring? It is imperative that my jQuery and ...

Creating a Macular Grid using JavaScript

Is there a way to create a macular grid using Javascript, with circles arranged in a 'V' shape pattern? How can we generate dotted circles in the shape of a 'V'? Any suggestions on how to tackle this challenge? If you want to visualiz ...

having difficulties retrieving the attribute value through jquery

I'm currently implementing this method on rowmouseevent. When I use $get(eventArgs.get_id()), the output is: <tr class="normal" data-value="normal" id="ctl00_ContentPlaceHolder1_UserGrid_grdusergrid_ctl00__0" style="height:30px;" /tr> How can ...

The transition kicks in as soon as the page finishes loading

I am attempting to incorporate transitions on divs when the page loads, but I am encountering difficulties getting it to work. template <header> <transition name="slideLeft"> <div v-show="loaded" class="contents content-left"&g ...

There is a button on my website that uses a small piece of Javascript to post a tweet, but unfortunately, it is not functional on mobile devices

Check out this link to view the demonstration - http://codepen.io/illpill/pen/VbeVEq function sendTweet(message, author) { window.open('https://twitter.com/intent/tweet?hashtags=thequotemachine&text=' + encodeURIComponent('"' + m ...