Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

benji's avatar
Level 6

Passing unique value from array using component vue.js

Hello,

I'm working on a favourites feature using the Spark framework. I'm falling down when it comes to passing the unique listing.id in the array. When the form is submitted it currently passes the last value in the array.

My Code.

        <form role="form">
          <input class="hidden" type="input" value="@{{ listing.id }}" v-model="form.listings_id">
          <button class="btn-naked" type="submit" @click="create(favourite)" :disabled="form.busy">Fav</button>
        </form>
    data() {
        return {
            favourites: [], listings: [],

            form: new SparkForm({
                listings_id: ''
            })
        };
    },

Any pointers would be greatly appreciated.

0 likes
1 reply
benji's avatar
Level 6

Update on this one.

Separated the components and now trying to pass the value in array listing.id via props but hasn't worked. Getting closer to a solution.

blade template:

<div id="app">

<listings>
</listings>

</div>

<template id="listing-template">
  <div class="container">
    <div v-for="listing in listings" class="panel panel-default">
      <div class="panel-body">
        <div>@{{ listing.name }} @{{ listing.id }}</div>

        <counter></counter>
        <counter></counter>
        <favourite listing="@{{ listing.id }}"></favourite>

      </div>

    </div>
  </div>
</template>

Vue.js

new Vue({
  el: '#app'
});

Vue.component('counter', {

  template: '<button @click="count += 1">{{ count }}</button>',

  data: function() {
    return { count: 0 };
  },


});

Vue.component('favourite', {
  props: ['listing'],
  template: '<form><input class="hidden" type="input" value="{{ listing }}" v-model="form.listings_id"></input><button @click="create(favourite)" :disabled="form.busy">Fav</button></form>',

  data: function() {
    return {
        form: new SparkForm({
            listings_id: ''
        })
    };
  },

  created() {
      this.getFavourites();
  },

  methods: {
    getFavourites() {
        this.$http.get('/api/favourites')
          .then(response => {
            this.favourites = response.data;
          });
        },

    create() {
        Spark.post('/api/favourite', this.form)
            .then(favourite => {
            this.favourite.push(favourite);

            this.form.id = '';
            });
        }
      }
});

Vue.component('listings',  {


    template: '#listing-template',

    data: function() {
      return {
            favourites: [], listings: [],

        };
    },

    created() {
        this.getListings();
    },

    methods: {
      getListings() {
          this.$http.get('/api/listings')
            .then(response => {
              this.listings = response.data;
          });
        }
      }
});

Please or to participate in this conversation.