Accessing an element from an array when a button is clicked using Vue.js

In my current project, I have set up a table that iterates through an array of objects.

    <table class="table table-striped" v-if="bins.length > 0">
        <thead>
        <tr>
            <th scope="col">#</th>
            <th scope="col">Location</th>
            <th scope="col" class="text-end">Action</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(bin, index) in bins" :key="index">
            <th scope="row">{{index + 1}}</th>
            <td ref="txtLocaton" contenteditable="false" v-text="bin.binlocation"></td>
            <td class="text-end">
            <div class="action-btn">
                <button @click="btnEdit"><fa icon="edit" /> Edit</button>
                <button><fa icon="trash" /> Delete</button>
            </div>
            </td>
        </tr>
        </tbody>
    </table>

The feature I am looking to implement is to toggle the contenteditable attribute from false to true when the Edit button is clicked.

This snippet shows the code for the data()

<script>
export default {
    data(){
        return{
            bins:[
                {
                    binlocation: '11 Garden Block, New City',
                },
                {
                    binlocation: 'Ali Towers, Lahore'
                },
                {
                    binlocation: 'The Mall Road'
                }
            ]
        }
    },

    methods:{
        btnEdit(){
          console.log(this.$refs.txtLocaton)
        }
    }
}
</script>

I initially considered using ref to achieve this functionality, but upon logging it, only the last item from the array is returned upon button click.

Answer №1

If you want to manage contenteditable keys, you can store them in an array called bins, with each key initially set to false:

[{
  binlocation: '11 Garden Block, New City',
  contenteditable: false,
}, {
  binlocation: 'Ali Towers, Lahore',
  contenteditable: false,
}, ...]

Next, connect the contenteditable attribute of a td element to these values (instead of directly assigning

false</code):</p>
<pre><code><td ref="txtLocaton" :contenteditable="bin.contenteditable" v-text="bin.binlocation"></td>

To toggle values when the 'edit' button is clicked, you can use the following methods:

<button @click="bin.contenteditable = !bin.contenteditable"><fa icon="edit" /> Edit</button>

or

<button @click="btnEdit(index)"><fa icon="edit" /> Edit</button>
btnEdit(index) {
  this.bins[index] = !this.bins[index]; 
}

Answer №2

Here is a helpful code snippet for you to try out. You can pass an index to your method and bind the contenteditable attribute to a data property:

new Vue({
  el: '#demo',
  data(){
    return{
      bins:[
        {binlocation: '11 Garden Block, New City',},
        {binlocation: 'Ali Towers, Lahore'},
        {binlocation: 'The Mall Road'}
      ],
      editable: null
    }
  },
  methods:{
    btnEdit(index){
      this.editable = index
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
.editable {
  border: 2px solid violet;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <table class="table table-striped" v-if="bins.length > 0">
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">Location</th>
        <th scope="col" class="text-end">Action</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(bin, index) in bins" :key="index">
        <th scope="row">{{index + 1}}</th>
        <td ref="txtLocaton" :contenteditable="index === editable" :class="index === editable && 'editable'" v-text="bin.binlocation"></td>
        <td class="text-end">
        <div class="action-btn">
          <button @click="btnEdit(index)"> Edit</button>
          <button> Delete</button>
        </div>
        </td>
      </tr>
    </tbody>
  </table>
</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

The toggleCategories function seems to be malfunctioning as it is only showing the sequence number as 0 in ReactJS

I am currently working on a portfolio using the React framework. One of the features I have implemented is a project page where multiple projects are displayed within tabs. However, I am facing some issues with the functionality. toggleCategories(){ ...

Using more than one button to activate a single Material-UI Popper component

I recently found myself in a situation where I needed to activate the Material-UI <Popper /> component from various clickable elements. According to the Popper component API on the official Material-UI website, setting the anchorEl property determine ...

When the internet reconnects, the browser will automatically retry making requests that previously failed

My current setup involves using GWT (Java to JavaScript) as the front-end, with an RPC mechanism (AJAX) to make server requests (Servlets are utilized for this purpose). Everything has been running smoothly so far. Recently, a test case was created which ...

Exploring the shine: implementing reflection in THREE.js

Is there a way to achieve a material that reflects other shapes from the scene? I attempted to use the reflectivity property but had no success in seeing any reflection. I found an example demonstrating this effect It seems like non-standard materials we ...

Troubleshooting issues with AES decryption in crypto.js

When using crypto-js to decrypt data, I am encountering an issue where the result is blank despite having valid keys that work for online AES decryption. var CryptoJS = require("crypto-js"); var key = '+MbQeThVmYq3t6w9z$C&F)J@NcRfUjXn'; var ...

Is it possible to invoke fancybox using a class selector?

I'm having trouble using fancybox on an element with this code: $(this).parent().parent().parent().find('.comments').fancybox(); Is it not feasible? Could it be because it's a class and not an id? I have multiple rows of items, so as ...

Integrating Vue Components into a React Micro Frontend with the Latest WebPack Version

Recently, I've delved into the world of micro frontends. To get started, I created a React micro frontend project named Micro-Shell-App using npx create-mf-app. Following that, I embarked on creating another project for Vue micro frontend called Secti ...

Object placed at the mouse position is shifted from its original location

I am working with ThreeJS in conjunction with MindAR, attempting to position an object where I click on the screen using my mouse. const mousePositionX = (e.clientX / window.innerWidth) * 2 - 1; const mousePositionY = -(e.clientY / window.innerHeight) * 2 ...

Allow users to upload .gltf or .glb 3D models using three.js

Greetings! I have recently embarked on the journey of learning about three.js I am curious to know if there is a way for the user to upload their .glb / .gltf 3d model and view it instantly on the canvas? My thoughts are leaning towards utilizing PHP, es ...

What is the best way to input information into my Google spreadsheet with React JS?

After using https://github.com/ruucm/react-google-sheets as a reference, I encountered a persistent gapi 404 error whenever I tried to run the code. It seems like the GitHub link might not exist, causing my app to fail. However, I could be mistaken. Is t ...

Secret button that remains unresponsive upon initial click after materializing

I am facing a problem with my two buttons in the HTML code. One button is supposed to plot data, while the other is meant to download data. The issue arises when the plot button has data and the Excel download button should become visible. Although this fu ...

Discovering the content within table cells by utilizing JavaScript functions linked to specific IDs

I am currently working on a project that involves a dropdown list: <select id="itemsList" onchange="gettingList()"> <option>Please choose an option</option> <option value="50">Shampoo</option ...

Incrementing an array of scores by a specified percentage and keeping it up to date

public class ScoreCard { private double[] scores; /** * * @param val * @param low * @param high * @return low if val < low, * high if val > high, * val if val is between low and high */ private double constrain(double val, int low, int hi ...

Error encountered with jQuery UI Modal box displaying at inappropriate times

There are multiple components to consider here. Firstly, the Javascript code in the head of the ASPX page is as follows: <!--//********************************** // Test modal popup //********************************** --> <script type=" ...

Attempting to load an image through an AJAX Request may prove to be unsuccessful

I am facing an issue with using an AJAX request to load a gif image from the following source: Despite my attempts, using the response on the image source like this: $('#cat-thumb-1').attr('src', 'data:image/gif;base64,' + d ...

Is there a way to identify and count duplicate data-items within an array, and then showcase this information using a react view?

If we have an array like this: [{id: 1, name: "chocolate bar"}, {id:2, name: "Gummy worms"}, {id:3, name:"chocolate bar"}] Is there a way to show on the dom that we have "2 chocolate bars and 1 Gummy Worms"? ...

Sharing data between multiple components in VueJS is an essential aspect of building scalable and maintainable

I am struggling with the code I have. main.js new Vue({ el: '#app', template: '<App/>', components: { App } }) App.vue <template> <div id="app"> // struggling to pass data to component <basics :r ...

The Postman application is unresponsive and the hashed password has not been created

I am currently attempting to create a hashed password using bcryptjs and then display that password using console.log for easy access and use. For testing my POST request, I am using Postman where my approach involves sending the request body with email a ...

The Quasar File Picker fails to upload images on iOS devices

I'm facing an issue with image uploading on mobile iOS (implemented using Capacitor). The image selection works, but when I select an image, nothing happens. Below is my input: <q-file v-model="avatarFile" accept=".j ...

Memory leakage in Internet Explorer as a result of JavaScript code

Recently, I created a website that utilizes jquery ajax to send an ajax request every minute in order to retrieve json data. This data is then parsed and added into the DOM. While this process runs smoothly on Chrome and Firefox, I noticed a significant m ...