Exploring the properties of individual Vue components on a single page with v-for loop

Struggling to render a Vue component in a Rails app by iterating through an array of data fetched via Ajax. The Slim template (index.html.slim) for the index page includes a custom_form_item component, where items represent custom forms data from Rails and each item is a component.

- content_for :head do
  = javascript_pack_tag "index_listing" 
  = stylesheet_pack_tag "index_listing" 

div.container data-behavior="vue"
  <custom_form_item v-for="item in items" v-bind:item="item" v-bind:key="item.id"></custom_form_item>

The script loads index_listing.js.coffee from javascript/packs. The created event loads the data for items.

import Vue from 'vue/dist/vue.esm'
import TurbolinksAdapter from 'vue-turbolinks'
import VueResource from 'vue-resource'
import CustomFormItem from '../components/custom_form_item.vue'

Vue.use(VueResource)
Vue.use(TurbolinksAdapter)

Vue.component('custom_form_item', CustomFormItem)

document.addEventListener('turbolinks:load', ->
  index_list_vm = new Vue(
    el: '[data-behavior="vue"]'
    data: () ->
      return {
        items: []
      }
    created: () ->
      console.log "inside created()"
      this.loadItems()
    methods: {
      loadItems: () ->
        self = this
        console.log "inside loadIems()"
        url = '...'
        self.$http.get(url).then((result) ->
          console.log "Got: "+result.data
          self.items = result.data
        )
    }
  )
)

Turbolinks.dispatch("turbolinks:load")

The component includes a delete button using a method to remove the respective item from items when clicked.

<template>
  <div class="custom_form_list_item">
    <label for="item_id">ID</label>
    <input id="item_id" v-model="item.id" readonly>
    <br/>
    <label for="item_name">Name</label>
    <input id="item_name" v-model="item.name" readonly>
    <br/>
    <div class="btn-group btn-group-toggle" data-toggle="buttons">
      <button type="button" class="btn-warning btn-sm" v-on:click="redirToEditURL(item.id)">
         <i class="fas fa-edit"></i>
      </button>
      <button type="button" class="btn-danger btn-sm" v-on:click="deleteForm(item.id)">
         <i class="fas fa-trash-alt"></i>
      </button>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    item: {
      type: Object,
      required: true,
    }
  },
  methods: {
    redirToEditURL: function(formid) {
      let url = ...
      window.location = url
    },
    deleteItem: function(key) {
      this.$delete(this.items, key);
    },
    deleteForm: function(formid) {
      let url = '...';
      let deleteListItem = this.deleteItem;
      $.ajax({
        url: url,
        method: "DELETE",
      }).done(deleteListItem.bind(this, formid));
    }
  }
}
</script>

<style lang="scss" scoped>
...
</style>

Encountering issues with props as it's expecting an object instead of an array. Also, facing confusion regarding passing the correct props into the component while fetching external data via Ajax.

Fixed! Solution: Use `self.items = result.data.data` as Rails passes the data as a JSON object {data: ...} that requires accessing the inner data object.

Answer №1

Give it a shot.

<div v-for="element in elements">
   <custom_input_element :element="element" :key="element.id"></custom_input_element>
</div>

Answer №2

Issue resolved! The fix involved assigning self.items the value of result.data.data (rails passed the result as a JSON object {data: ...}, requiring result.data.data).

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

Issue with AngularJS: The select dropdown fails to update the selected option when the bound scope variable changes

I am facing an issue with a select control in my Angular app. The options for the select are generated dynamically from an array of objects in the scope. When I try to pre-select a specific option on app init by changing a bound variable on the scope, it d ...

Tips on pausing a moving image from left to right and restarting it later

Is there a way to pause the left to right moving image at the end and then restart the loop? I tried utilizing this website link for assistance: https://www.w3schools.com/cssref/tryit.asp?filename=trycss3_animation-delay Unfortunately, I couldn't fi ...

What are the steps for scheduling asynchronous tasks using Promises in Node.js?

As a beginner in Javascript, I am struggling to understand how to execute my functions sequentially. My goal is to use Promises to accomplish this task. I am currently following a tutorial on creating a chat bot for Facebook Messenger. Essentially, I want ...

Incorporate a JavaScript form into a controller in MVC4

I'm facing an issue where I need to trigger a JavaScript function from within a controller method in my project. Here is the code snippet that I am using: Public Function redirectTo() As JavaScriptResult Return JavaScript("ToSignUp()") E ...

Different approach for searching and modifying nested arrays within objects

Here is an example of the object I am working with: { userId: 111, notes: [ { name: 'Collection1', categories: [ { name: 'Category1', notes: [ {data: 'This is the first note& ...

Exploring the world of jQuery and Ajax to retrieve a full HTML framework

I'm a beginner in jQuery and JavaScript programming. While I've managed to use jQuery for my Ajax calls, I'm facing an issue that has me stumped. When making an Ajax call, I'm trying to return a complete HTML structure, specifically a ...

Add the file retrieved from Firestore to an array using JavaScript

Trying to push an array retrieved from firestore, but encountering issues where the array appears undefined. Here is the code snippet in question: const temp = []; const reference = firestore.collection("users").doc(user?.uid); firestore .collec ...

WebApp specifically designed for iPads that mimics the functionality of a swipe

I am in the process of developing a full-screen web application for an iPad that will showcase a series of images in a slider format. The users should be able to swipe between the images and click on one to view it in detail. Below is an example showcasin ...

Adding a class to the body element in an HTML file using AngularJS

Greetings! Currently I am in the process of developing a web application using AngularJS SPA, which supports both English and Arabic languages. I am facing an issue with adding RTL and LTR properties by applying classes to the body HTML element in my app.j ...

Struggling to generate a functional link with Laravel and Vue?

For the past few days, I've been facing a problem. The issue I'm encountering is this: I have created a link in my .vue page to download a simple PDF file: <a href= {{ asset('download/form.pdf') }}> Download here. </a> (Th ...

Remove elements from an array based on the indices provided in a separate array

1) Define the array a = [a,b,c,d,e,f,g,h,i,j]; using JavaScript. 2) Input an array 'b' containing 5 numbers using html tags. This will be referred to as the 'b' array. 3) Insert elements into array 'b' ensuring they are alwa ...

Is it permissible to use Aloha editor GPL v.2 on a business website?

While researching the licensing of Aloha Editor, I came across some confusing information. I found a reference to another editor under LGPL: However, I couldn't find a clear answer on whether I can use Aloha JS code on a commercial website with GPL v ...

What is the best method for dynamically increasing the data in a shopping cart?

My goal is to stack cart items dynamically every time the addProduct() function is called. I've successfully captured the data, but I'm facing an issue where the quantity always remains at 1 on each function call. Here's the logic I've ...

Preserve the previous and current state within a React application

Within my code, there is a state called newuser that undergoes changes based on the inputs entered into the input fields. This change occurs once all input fields are filled and the submit button is clicked. The goal I have in mind is to store the current ...

Show items in the sequence of clicking

Is there a way to display elements in the order they're clicked, rather than their order in the HTML using jQuery? For example: CSS code: .sq{ display:none; } HTML Code: <a href="#" id="1">A</a> <a href="#" id="2">B</a> ...

Joi validation that focuses on required array elements while disregarding nested keys

Why is my Joi array required validation not detecting an empty array? I have an array called userData that contains objects with keys dateMilli and value. Despite adding required validations everywhere, passing an empty array [] for userData does not resul ...

Ways to address the npm error: Missing script 'dev'

After successfully installing Node.js, I proceeded to install cnpm using the following command: npm install -g cnpm --registry=https://registry.npm.taobao.org cnpm install However, when I attempted to run the command cnpm run dev, an error occurred: npm ...

Encountering issues when attempting to establish the initial date of a react DatePicker based on the user's timezone

I am currently working on a React project and facing an issue with setting the default date of a DatePicker component to the user's timezone received from an API. Despite several attempts, I keep encountering an error whenever I try to inject the date ...

JSON response is not being successfully passed in PHP Ajax form validation

I've been struggling to solve my code for the past few days but haven't had any success. I'm attempting to validate my login form using AJAX, however, it seems like there's an issue with my Jquery AJAX script. Every time I try, the con ...

Indeed, conditional validation is essential

I have encountered an issue with my schema validation where I am trying to validate one field based on another. For example, if the carType is "SUV", then the maximum number of passengers should be 6; otherwise, it should be 4. However, despite setting u ...