Search code examples
javascriptarraysvue.jsnuxt.jscodesandbox

How to retrieve value passed to a prop from an array VueJS/NuxtJs


CodeSandbox

Reference Video

I'm trying to retrieve a value that was dynamically created and passed to a prop.

After clicking "add card" and clicking on one of the created cards, the goal is to pass the value(prop: randomNum) into a variable(num1).

In the Sandbox, I'm able to get the value of the Id which was also created dynamically.

methods: {
//"emits" or Allows value of the id prop in Array to be reached from parent?
select() {
  this.$emit("select", this.id);
}

Above Code from nested /component/card.vue

 <card
    v-for="cards in cardArray"
    :key="cards.id"
    :id="cards.id"
    :randomNum="cards.randomNum"
    @select="selectCard"
    :selectedCard="selectedCard"
    :playable="cards.playable"
    :visable="cards.visable"
  ></card>
  <h1>{{num1}}</h1>
  <h1> {{ selectedCard }} </h1>
 ----------
data() {
return {
  cardArray: [],
  selectedCard: null,
  num1: null,
----------
methods: {
    selectCard(cards) {
      this.selectedCard = cards;
    }

Above code from the main /component/hand.vue

From my understanding, in this case, cards evaluates to this.id?

How can I set num1 to equal cards.randomNum(second item in payload) The same way that selectedCard evaluates to cards(cards.id)

I've tried variations of "item.Array" and using $emit on this.randomNum the same way it was used to $emit this.Id which doesn't work, how can I properly do this?

 //in card hand componenet
select() {
  this.$emit("select", this.id);
this.$emit("select", this.randomNum);

} 
//in card hand componenet
selectNum(cards.randomNum) {
  this.num1 = randomNum;

Solution

  • You can either use two separate events or just pass an object with multiple values.

    two events:

    select() {
      this.$emit("selectId", this.id);
      this.$emit("selectNum", this.randomNum);
    } 
    

    or pass object with multiple values

      this.$emit("select", {id:this.id, randomNum:this.randomNum});