Sharing information between two different sections

In component1.vue, the code looks like this:

  export default {
    data () {
      return {
        editItemNumber: null,
        editBreakdownNumber: null
      }
    }

Meanwhile, in component2.vue, there is a table that is filled with an array of items.

Within that table, there is an edit button. Each row in the table has an itemNumber value, which needs to be assigned to the editItemNumber in component1.vue when that particular row is clicked.

<b-table show-empty bordered striped hover :items="itemTableList" :fields="fields">
  <template slot="actions" scope="row">
<b-btn variant='success' size="sm" @click.stop="edit(row.item,row.index,$event.target)">Edit</b-btn>
</template>
</b-table>

Originally, all of this functionality was on one component and I simply called an edit function that repopulated the v-models with the contents of the selected row. But now that everything is split among components, I am unsure how to modify it to achieve my current task.

I have limited experience with JavaScript, Vue, and web development in general. As a .NET developer who has been asked to assist with web projects, I am struggling to adapt. Any guidance would be greatly appreciated.

Answer №1

When it comes to transferring data between components, using events is the recommended approach.

Typically, you would utilize props to send data from a parent component to a child component, and use events to transmit data from a child back up to its parent.

For instance, the edit method of C2 could look something like this:

edit(item, index, target) {
    const payload = {
        item,
        index,
        target
    };

    this.$emit('edit', payload);
} 

Subsequently, you just need to listen for that event in C1. Take note of the @edit attribute: this signifies that when the edit event is triggered from component-one, execute my "edit" method.

<template>
<div>
   <p>{{ editItemNumber }}</p>
  <component-two @edit="edit" />
</div>

<script>
export default {
data () {
  return {
    editItemNumber: null,
    editBreakdownNumber: null
  };
},

methods: {
    edit(eventPayload) {
        this.editItemNumber = eventPayload.item.editItemNumber
    }
}
</script>

If both C1 and C2 are children components of the same parent P, the concept remains similar. However, C1 cannot directly listen to C2. Instead, P will be the one listening for the edit event and conveying the necessary changes down to C1 through its props.

The documentation on Vue components is highly informative, especially the sections covering props and custom events. https://v2.vuejs.org/v2/guide/components.html

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

Placeholder for empty values in Angular UI mask

Currently, I have implemented the angular ui mask directive for a date field. However, it is inserting underscores as a placeholder. Is there a way to display nothing in the placeholder instead? ...

Having trouble with AJAX integration when adding two products to the cart? Looking for a solution to resolve this issue?

In the cart view page, I have noticed that when there is only one product in the cart, I am able to increase and decrease the quantity by clicking on the + and - buttons. However, if I add more than one product to the cart, these buttons do not work for an ...

Ending the loop of a jQuery JSON array when reaching the final row

I have a function that retrieves a JSON array and shows the results as a list with ten items. However, if there are fewer than ten results, it starts over from the beginning. This is my code: $.ajax({ url: 'http://www.entertainmentcocktail.com/c ...

code snippet for callback function in javascript

Recently, I've been working on a project with angularjs and phonegap and stumbled upon this interesting code snippet. While I have a basic understanding of what it does, the inner workings are still a bit unclear to me. Since I'm still getting fa ...

Unable to make a successful POST request using the JQuery $.ajax() function

I am currently working with the following HTML code: <select id="options" title="prd_name1" name="options" onblur="getpricefromselect(this);" onchange="getpricefromselect(this);"></select> along with an: <input type="text" id="prd_price" ...

Using asp.net and c# in tandem with javascript is a powerful

((LinkButton)e.Item.FindControl("my_label_name")) .Attributes.Add("onclick","javascript:myCustomFunction('" + dbValue1 + "','"+dbValue2+"')"); I implemented this code (located in my default.aspx.cs) ...

The challenge of vertically aligning text in a dynamically generated div

Currently, I am in the process of developing a straightforward application that allows for the dynamic addition of students and teachers. I am dynamically adding divs with a click function. To these dynamically created divs, I have assigned the class "us ...

obtain the $http service and make a request

I am trying to access the $http service in AngularJS and execute the get function within my custom asyncAction function call without involving any HTML or Bootstrap. Can anyone help figure out a way to achieve this without manually inserting markup or trig ...

Can you explain how to create a function in Angular that accepts a number as an argument and then returns the square of that number?

I am working with an array of numbers and I want to show each number in the list along with its square value. To do this, I need to create a function that takes a number as input and returns its square as output. Here is what I have attempted so far: co ...

Using Vue to pass the v-for index from a parent component to a child component

Despite conducting thorough research, I am unable to find a satisfactory answer. Below is the code for my parent and child components. How can I pass the index from the v-for loop in the parent component to the child component so that it can be utilized th ...

Exploring Data Retrieval and Presentation in React JS

I have successfully stored data in my database. However, I am curious about how to display/render the retrieved data on my screen after making a fetch request. When adding data, I can easily push it to render on my page. But my question is, after running ...

Invoking a PHP function file through Ajax

Currently, I am utilizing Ajax with Bootstrap Modal to retrieve content from a Database. One of the functions in my functions file is responsible for verifying the existence of a remote file: function checkRemoteFile($url) { $ch = curl_init(); cur ...

Issue with displaying JavaScript file path on master page in ASP.NET resulting in a 404 error status

Despite correctly specifying the JavaScript file path in the ASP.NET master page, the browser console is displaying a 404 error for the JavaScript files. It seems that the browser is unable to locate the specified JavaScript files. Here is the code being ...

Server request successful, but CORS error occurs in browser

When I make an HTTP POST request to the Microsoft login in order to obtain an access token for use with the mail API, the request is successful but my code still goes to the error clause. requestAccessToken(code: string) { console.log("Requesting access t ...

"Discover the step-by-step process for customizing the icon colors within Bootstrap components

I successfully incorporated a dark mode into my Vue project built with Bootstrap 5.2. However, I am facing an issue while trying to change the color (to be white) of the two icons below: The first one is from a form-select https://i.sstatic.net/5ayvH.png ...

Move a div in front of a fade-toggle

I am currently working on a website primarily using PHP, but I have very little knowledge when it comes to JavaScript/jQuery. I managed to create a feature where I press a button and a div fades in, but it abruptly moves the divs under it. Is there a way f ...

Having difficulty requesting an API in Next.js that relies on a backend cookie

1: When a user logs in, I generate a refresh token and create a cookie using 'cookie-parser'. This cookie is then sent to the path '/user/refresh-token' res.cookie('refreshtoken', refreshtoken, { httpOnly: true, ...

Differences between variable scope in Node.js and web browsers when running JavaScript code

When it comes to browser, different JavaScript files share one scope: a.js: var a=1; //by adding "var", we prevent it from becoming a global variable. b.js: console.log(a) //even though a=1, b.js can still access this variable! In Node.js: a.js .... b ...

The catch block seems to be failing to capture the errors thrown by the fetch API

I am facing an issue with my code where the fetch method, enclosed within a catch block, fails to capture errors. Despite attempting various error handling approaches on my node backend, the problem persists. https://i.stack.imgur.com/0reJj.png const e ...

What is the best way to compare the previous and next values in React?

When working with the code snippet below to send a list of values to another component - React.createElement("ul", null, this.state.stock.map(function (value){ return (React.createElement(Price, { price: value })) }) ) the values are then sent t ...