JavaScript-generated buttons fail to trigger VueJS functions

I have a function that creates buttons for each item in a list, and each button is supposed to execute a function in the App.vue file when clicked.

The issue I am facing is that neither the onclick nor the v-on:click methods are functioning as expected.

Here is the code snippet:

    await resetView();
    // document.getElementById("projSelLb").style.display = "none";
    var projects = await detaStorage.getAllProjects();
    var parentDiv = document.getElementById('projectsDetaDiv');
    projects.forEach(function(item) {
      var div = document.createElement('div');
      div.innerHTML = `<button type="button" class="btn btn-primary" style="margin-top: 12px;" @click.native="loadFromDeta(String(item))">${item}</button>`;
      parentDiv.appendChild(div);
    });
    // document.getElementById("projSelLb").style.display = "block";
    document.getElementById("spinnerGetProj").style.display = "none";

  async function resetView() {
    // document.getElementById("projSelLb").style.display = "none";
    document.getElementById("spinnerGetProj").style.display = "block";
    document.getElementById('projectsDetaDiv').innerHTML = null;
  }

function loadFromDeta(name) {
  workspaceClear();
  var data = detaStorage.getProjectData();
  Blockly.Xml.domToWorkspace(data.xml, foo.value.workspace);
}

Answer №1

If you are interested in manually creating elements in Vue, you will need to utilize the render() function. While there are practical uses for this approach, I recommend sticking to the traditional Vue style where you separate template and data operations for cleaner and more maintainable code.

In your template, you can achieve the same DOM operations by using v-if to toggle the loading spinner visibility and v-for to generate buttons from a list:

<div v-if="loading" id="spinnerGetProj"/>
<div v-else v-for="item in projects" :key="item">
  <button
    type="button"
    class="btn btn-primary mt-4"
    @click="loadFromDeta(item)"
  >{ item }</button>
</div>

If you are using Vue 3 with the composition API, the corresponding script section would look something like this:

const projects = ref([])
const loading = ref(true)

const loadProjects = async() => {
  loading.value = true
  projects.value = await detaStorage.getAllProjects()
  loading.value = false
}

Simply call loadProjects() and everything will fall into place. I hope this information is helpful for 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

What is the best way to create a responsive div containing multiple images?

I am working on a slider and my approach is to create a div and insert 4 images inside it. The images will be stacked one above the other using position: absolute, with a width of 1013px, max-width of 100%, and height set to auto for responsiveness. The is ...

Understanding the application of JSON data can be simplified by following these

I am looking to manipulate dates by either adding or subtracting them, but I am unsure of how to extract the dates from the other data present. var fetch = require('node-fetch'); fetch('https://api.nasa.gov/planetary/earth/assets?lon=100.7 ...

React: The received value for the prop type must be a function, but it was an object

I'm stuck trying to make sense of this error message, and my online search has hit a dead end. Any insights would be greatly appreciated! Attention: Prop type validation failed - expected prop type `leoInfo` to be a function from the `prop-types` pack ...

A singular Vuejs Pinia store utilizing namespaced actions

Is it possible to separate pinia actions into two distinct namespaces, allowing access through properties n1 and n2 like this: // current store.n1a('hi') store.n2b() // wanted store.n1.a('hi') store.n2.b() // cumbersome workaround: sto ...

Tips for locating the existence of an Azure File in NodeJS

Currently, my project involves utilizing azure file storage along with express JS for creating a backend to display the contents stored in the azure file storage. The code I am working on is referencing this documentation: https://learn.microsoft.com/en-u ...

Node is currently posing a challenge for the installation of packages

I am currently facing an issue while setting up my raspberry pi 3. I am attempting to install and execute a node code, but I encountered a problem during the installation of packages using npm. After trying multiple times with different versions of node ( ...

Minimize the visibility of the variable on a larger scale

I have a nodejs app where I define global variables shared across multiple files. For example: //common.js async = requires("async"); isAuthenticated = function() { //... return false; }; //run.js require("common.js"); async.series([function () { i ...

Collect data entered into the input box and store them in an array for the purpose of

I need assistance with a code that involves input boxes for users to enter numerical values, which are then stored in an array. My goal is to add these values together and display the sum using an alert when a button is clicked. However, I am struggling to ...

JSDOM failing to retrieve complete list of elements from webpage

I'm currently struggling with a simple webscraper using JSDOM. Here's the code snippet I've been working on: const axios = require("axios"); const jsdom = require("jsdom"); const { JSDOM } = jsdom; let v = "15" ...

Discover the steps for incorporating the substring method into JavaScript to manipulate input strings

Is there a way to extract the specified portion of text from an input string using HTML and Javascript? <!DOCTYPE html> <html> <body> <input type="text" value="exampleString"></input> <button onclick=& ...

JavaScript is unable to post content or access elements

Check out the following code: <div class="col-2"> <div class="input-group"> <label class="label">Name</label> <i ...

Re-sequence a contiguous array by mapping and filtering its elements

Within my React code, I have a list component that utilizes array.map to display a list of items. The list items have alternating backgrounds; every other item's background color is determined by whether the id field from the data structure is even o ...

Splitting an array into multiple arrays with distinct names: A step-by-step guide

I have a data set that looks like this: [A,1,0,1,0,1,B,1,0,0,1,A,1]. I want to divide this array into smaller arrays. Each division will occur at the positions where "A" or "B" is found in the original array. The new arrays should be named with the prefix ...

Using jQuery's .remove() function removes all of the children from the container, rather than just one at

For my latest project, I am focused on creating a seamless full-page transition using AJAX calls. The challenge I'm facing is removing content from the DOM when loading in a new page. Despite adding a unique class or ID to the element, the .remove() f ...

A for loop is executed after a console.log statement, even though it appears earlier in the code

When this specific block of code is implemented var holder = []; const compile = () =>{ let latitude = 0; let longitude = 0; for (let i = 0; i < holder.length; i++) { Geocode.fromAddress(holder[i].city).then( (response ...

Simplified method for utilizing plugins with the composition api in vue 3

When incorporating vuex or vue-router as plugins in Vue and utilizing the options API, access to these plugins can be achieved using the this keyword. main.js import { createApp } from 'vue'; import i18n from '@/i18n'; import router fr ...

Showing the total quantity of products, reminiscent of a virtual shopping basket

I am trying to show a number similar to how a shopping cart displays items. The php code I was given currently shows a cookie value, which is mostly functional. However, if you encounter errors while adding items to the cart, it increases the cookie count ...

Storing customer information securely on the server with the help of Node.js

After spending some time experimenting with Node.js on my local machine, I've realized that my understanding of HTTP requests and XHR objects is quite limited. One particular challenge I've encountered while using Node is figuring out how to effe ...

Animating a div in CSS3 to expand horizontally from left to right without affecting its original position

I am currently in the process of developing a calendar using HTML, CSS, and JavaScript. The main purpose of this calendar is to showcase upcoming and past events. However, I am facing difficulties in ensuring that my event blocks occupy the remaining space ...

Encountering a problem when verifying if the data is in JSON format using JavaScript

I'm using JavaScript to determine whether an input value is in JSON format, but I've encountered a problem with a specific value. Below is my code explanation. isJSON = async(str) => { try { return (JSON.parse(str) && !!str); ...