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.