Tips for sending a prop to a parent component in Vue.js

Currently, I'm working on a Vue-Tac-Toe application just for fun but I've hit a bit of a roadblock.

Please take a look at the screenshot for better context. https://i.sstatic.net/AZtvH.jpg


The Issue: How can I pass the prop cellRow to the component Field.vue?

What I Need: Each Field should have a unique identifier, such as the top-left tile (the first one) being recognized as cellRow: 0 & cellId: 0. This information is necessary for checking tic-tac-toe wins (3 in a line etc.).


GameField.vue: We use a row and cell-based layout.

<template>
  <div id="game-field">
    <div class="container">
      <template v-for="(rows, index) in 3">
        <Row :cell-row="index" />
      </template>
    </div>
  </div>
</template>

<script>
import Row from './Row.vue';

export default {
  components: {
    Row,
  },
  data() {
    return {};
  },
};
</script>

<style lang="scss" scoped>
.container {
    width: 400px;
    margin: 10% auto 0;
}
</style>

Row.Vue: Each row contains 3 Fields numbered from 0-2.

<template lang="html">
  <div class="row">
    <Field
      v-for="(fieldId, index) in 3"
      :key="fieldId"
      :cell-id="index"
    />
  </div>
</template>

<script>
import Field from './Field.vue';

export default {
  components: {
    Field,
  },
  props: {
    cellRow: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {

    };
  },
};
</script>

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

Field.vue:

<template lang="html">
  <div class="cell">
    <slot />
  </div>
</template>

<script>
export default {
  props: {
    cellId: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {};
  },
};
</script>

<style lang="scss" scoped>
  .cell {
    margin: 1px 3px -3px -1px;
    width: 100px;
    height: 100px;
    background-color: white;
    display: inline-block;
    cursor: pointer;
  }
</style>

Answer №1

If I grasp the question correctly, you have the ability to pass the cellRow prop from the Row component directly as a prop of the Field component.

Row (passing cellRow as a prop to Field)

<template lang="html">
  <div class="row">
    <Field
      v-for="(fieldId, index) in 3"
      :key="fieldId"
      :cell-id="index"
      :row-id="cellRow" // passing row index to Field component
    />
  </div>
</template>
...

Field

...
<script>
export default {
  props: {
    cellId: {
      type: Number,
      default: 0,
    },
    rowId: {  // defining new prop type
      type: Number,
      default: 0,
    },
  },
  ...
};
</script>

Check out this quick demo:

Vue.config.devtools = false;
Vue.config.productionTip = false;


Vue.component('Row', {
  template:
    `
<div class="row">
  <Field
    v-for="(fieldId, index) in 3"
    :key="fieldId"
    :cell-id="index"
    :row-id="cellRow"
  />
</div>
`,
  props: {
    cellRow: {
      type: Number,
      default: 0
    }
  }
})

Vue.component('Field', {
  template:
    `
  <div class="cell">
    <p>Row Id: {{ rowId }}</p>
    <p>Cell Id: {{ cellId }}</p>
  </div>
`,
  props: {
    cellId: {
      type: Number,
      default: 0
    },
    rowId: {
      type: Number,
      default: 0
    }
  }
})

new Vue({
  el: '#demo',
  template:
    `
<div id="game-field">
    <div class="container">
      <template v-for="(rows, index) in 3">
        <Row :cell-row="index" />
      </template>
    </div>
  </div>
`
})
.cell {
  margin: 1px 3px 3px 1px;
  width: 100px;
  height: 100px;
  background-color: gray;
  display: inline-block;
  cursor: pointer;
  color: white;
  padding: 5px;
}
.container {
    width: 400px;
    margin: 10% auto 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo"></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

Send an array from PHP to jQuery using AJAX, then send the array back from jQuery to PHP

I am facing a dilemma where I am passing an array from PHP to jQuery AJAX using `json_encode` and storing it in an empty array declared in the jQuery script as `var myarr = []`. Later in the same script, I am sending the same array `myarr` back to the PHP ...

Is there a way to trigger a function from a specific div element and showcase the JSON data it retrieves in

I am working with a React JS code page that looks like this: import React, { useState } from "react"; import { Auth, API } from "aws-amplify"; function dailyFiles(props) { const [apiError502, setApiError502] = useState(false); // Extracted into a re ...

Delaying the intensive rendering process in Vue.js and Vuetify: A comprehensive guide

Recently, while working on a project with Vue.js 2 and Vuetify 2.6, I encountered an issue with heavy form rendering within expansion panels. There seems to be a slight delay in opening the panel section upon clicking the header, which is most likely due t ...

A guide on extracting the values of checked checkboxes by their ID using javascript

I'm currently attempting to extract the values of selected checkboxes. These checkboxes have distinct IDs because they are specified within a modal window. <input type = 'checkbox' id = 'audience_Name-$row[asset_ID]' value = &a ...

Jquery Validation Plugin - Specifically for validating numeric inputs in specific situations

I am currently working on implementing validation using jQuery Validate for a numeric value, but only when a specific radio button is checked. If the radio button is not checked, the field should be required and allow alphanumeric values to be entered. How ...

Mapping an array based on specific conditions

When using my photo gallery app, I faced a challenge in mapping an array of images based on the user-selected album name. The current setup works perfectly for the 'Cambodia' album where all images are correctly logged in the console after mappin ...

Leverage React Native elements within a Meteor React-based website

Currently, we are in the process of developing a Meteor React web application that will be displayed within a web view on a react native app. While this arrangement may seem unconventional, it is due to time constraints and the fact that the react native a ...

Modify the bootstrap form dynamically in response to the user's input. Update the form layout instantly as the user types, with no need for clicking any buttons

Imagine a scenario where, as soon as you enter your credit card number, the form automatically undergoes a change without requiring a button click, similar to how a credit card logo pops up. The form detects changes instantly after the input field has be ...

Error: Failed to find the location because geolocate has not been defined

I searched extensively online for a solution to my problem without success, so I am reaching out to seek your assistance. I am attempting to utilize the Google Address auto-complete API within an asp.net core framework. In my razor file, I have included: ...

By changing the name of my file to .js.erb, I am able to seamlessly incorporate erb syntax within my javascript code, but this

Currently, I am using chessboard-0.3.0.js in a rails application. Due to the rails asset pipeline setup, I've had to make adjustments to the js code specifically related to rendering images, such as Pieces. In line 445 of chessboard.js, it states: c ...

Steps to avoid IE11 prompt (Do you really want to leave this site)

In the midst of making a webpage, I find myself faced with the peculiar issue of only having a dropdown to select. To make matters worse, when attempting to navigate to the next page in IE11, a pesky message pops up. Curious about the default behavior of ...

Turning off the transpiler in Vue Webpack to simplify the debugging process

Debugging in Vue can be quite challenging, especially when it comes to setting breakpoints and stepping through the code. The issue seems to stem from the transpiling of javascript ES6/ES2015/ES2016/ES2017 to ES5. While source maps provide some assistance, ...

Tips for Maximizing the Efficiency of a Search in a Complexly Nested Object

I am faced with a complex JavaScript object structure that represents hierarchical data. This object contains multiple levels of nested children, and I have the task of searching for a specific value within this intricate structure. Let's take a look ...

Utilizing the model value either by directly accessing it or by passing it as a parameter to a function from the

After exploring both options, I am still unsure which one is more technically superior in terms of functionality. One method involves passing a model value from the front end HTML to a function by calling ng-click. View: <input type="text" ng-model= ...

AngularJS RESTful Routing Masterclass

I am in the process of organizing my application using the Restful/Ruby convention /<resource>/[method]/[id]. In the past, when working with a server-side MVC framework like CodeIgniter, I would dynamically route based on the URI: For example: www. ...

Tips for adding and removing active class with navbar links using JavaScriptonclick

I need help with toggling the "li-active" class on my navigation bar links. Currently, when I click on a link, the "li-active" class is transferred from the previous link to the newly clicked link instead of removing it first. Can someone please assist me ...

I aim to generate a JavaScript string that, when placed within a div tag, will display as a list

I need assistance with formatting a string that contains a list of items to display in a specific way within a div tag using JavaScript. The string has multiple items that I wish to show as a bulleted list. Here is an example of the string: const items = & ...

Proper method for updating a component prop in Vue.js from within its method

Here is the code snippet for a Vue.js component: var list = Vue.component('list', { props: ['items', 'headertext', 'placeholder'], template: ` <div class="col s6"> <div class="search"> ...

Retrieve information from both the client and server sides within NextJS

Looking to integrate a third-party API for data fetching in certain components within my NextJS project. The goal is to have the server pre-render these components with the API for optimal SEO benefits, but also enable client-side fetching of component pro ...

CKEditor displays the return value of an object as `[object Object]

After enabling CKEditor for my textarea, I have encountered an issue where instead of displaying the typed text, CKEditor returns [object Object]. Can anyone assist me in troubleshooting this problem? I appreciate any guidance provided. I have utilized th ...