What is the best way to transfer information (specifically the length of an array of books) from one component to another in Vue

I am currently working on a single page that is responsible for showcasing Books (child component) on the Dashboard (Parent-component).

In the DisplayBooks component, the data is fetched from the backend and stored in a books array. I then iterate through this array using a loop to display the books on the UI page. Now, I need to pass the length of the books[] array to the Dashboard component and bind it to the template section. Please guide me on how to achieve this.

Dashboard.vue

<template>
<div class="main">
    <div class="navbar navbar-default navbar-fixed-top">
        ...
    </div>

    <script>
    ...
</script>

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

DisplayBooks.vue

<template>
<div class="carddisplay-section">
      
    ...
  
</div>
</template>

<script>
...
</script>

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

Answer №1

When it comes to binding data from a child component to a parent component, the solution lies in two-way binding.

If you are using Vue 2, the key is to use ".sync". Check out the helpful resource linked below for more information.

https://v2.vuejs.org/v2/guide/components-custom-events.html#sync-Modifier

Here's an example:

Parent Component

...
    <DisplayBooks v-show="flag==='noOrder' && shownComponent==='DisplayBooks'" @update-books-count="(n)=>booksCount=n" :count.sync="booksCount"/>
...

...
watch:{
booksCount(newCount){
  console.log(this.booksCount)
}
...

Child Component

...
props: ['count']
...

...
mounted() {
    service.userDisplayBooks().then(response => {
        let data = response.data;
        data.map(function(obj) {
            obj.hover = false;
            return obj;
        });

        this.books.push(...data);
        this.$emit('update:count', this.books.length)
        return response;
    })
},
...

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

the issue of button click events failing to trigger within deeply nested divs

Hey there, I'm currently working on creating three buttons with a shared text area. Each button is supposed to display a different message in the shared text area when clicked. I was able to achieve this functionality in a codepen which you can check ...

Preload-webpack-plugin does not support pre-fetching files

I have a query about prefetching and preloading content. In my vue app, I noticed that after building, I have duplicate files loaded in my dist/index.html file. Here is an example: Additionally, the "scripts" are not being preloaded/prefetched as expec ...

What are the connections between objects in ReactJS?

I have an array containing objects, and I want to extract a specific value from another array by using the key inside it as a search parameter. Specifically, I need to retrieve the name of an item based on its ID. The primary array: this.setState({ offer ...

What is the best way to propagate a react component's props to options following an apollo-client mutation?

How can you effectively pass a react component's props to options after performing a mutation using apollo-client? I am currently utilizing react in conjunction with apollo-client. Within a specific component, I am executing a delete mutation and the ...

Ways to transform date into a different structure using JavaScript

Fetching a date from an API gives me this format: 2017-04-20T07:00:00Z How can I convert it to the following format? 20.04.2017 I am using React to render the date: <div>{props.data.day}</div> I attempted to use toISOString().slice(0, 1 ...

What are the steps to implement a mask for CPF or CNPJ using MaskedInput in ReactJS?

Just starting out with ReactJS and trying to implement a dynamic mask for my form input field. The goal is to have a mask that can handle both CPF and CPNJ formats: CPF format: 111.111.111-11 CNPJ format: 11.111.111/1111-11 Regex for validation: /(^&bs ...

When I click the mouse, my drawing function starts lines from the top left corner instead of the latest point

http://codepen.io/FreelanceDev/pen/kLpJSf?editors=1010 You can find my CodePen project through the provided link. While the HTML and CSS elements are working correctly, I am facing issues with the JavaScript functionality. The desired outcome should be d ...

Modifying the input placeholder color with ng-style

I am working on setting the color of my input placeholder using a dynamic color defined in a $scope variable in my controller for my HTML code. The $scope variable is structured as follows: $scope.primaryColor={"color":colorVar}; //colorVar represents th ...

Creating scrollable content using JavaScript within a container with a hidden overflow

I am looking for a solution to efficiently display numerous image thumbnails within a limited space. My plan is to organize the thumbnails into 3 columns with an undetermined number of rows. I intend to place this content inside a viewport div, structured ...

Issue: The function `this.isModified` is not recognized as a valid function

Encountering an unusual problem. This code snippet is causing an error and it relies on arrow functions UserSchema.pre('save', next => { const SALT_FACTOR = 5; if (!this.isModified('password')) return next(); bcrypt.genSalt ...

Is there an equivalent of HtmlSpecialChars in JavaScript?

It seems that finding this is proving more difficult than anticipated, even though it's such a simple concept... Is there an equivalent function in JavaScript to PHP's htmlspecialchars? While it's possible to create your own implementation, ...

Animate the CSS when the content is within the viewport using pagepiling.js integration

I'm currently working on animating content as it enters the viewport. However, I've encountered an issue where jQuery (used to check if the content is in the viewport) isn't functioning properly alongside pagepiling.js (). I suspect this mig ...

Discover the white circle search bar display

I am attempting to implement a circular reveal animation to display the search toolbar in my web application using CSS and JavaScript. My goal is to achieve a similar effect as seen on Whatsapp for Android. https://i.sstatic.net/YE242.jpg I have successfu ...

Tips for aligning placeholder and text at the center in a React Material UI TextField

Existing Layout: https://i.stack.imgur.com/Zv4Tg.png Desired Layout: https://i.stack.imgur.com/Xuj6O.png The TextField element is displayed as follows: <TextField multiline={false} autoFocus placeholder={props.defaultAmt} ...

Contrasting include versus block in Jade

Can you explain the distinction between blocks and include in Jade template creation? How do you determine when to use each one? ...

Enhancing MongoDB query efficiency using Promise technology

At the moment, I am deeply involved in a personal project that is presenting a challenge with two different approaches to querying MongoDB. CustomerSchema.methods.GetOrders = function(){ return Promise.all( this.orders.map(orderId => Order. ...

How can I simulate mouse position in a UIWebView?

Can the mouse position (x,y) for HTML-5 elements on a UIWebView be programmatically set using stringByExecutingJavascript in order to trigger hover, mouse over, and other interactions? ...

The functionality of Google Map APIs is not compatible with Angular views

I'm currently attempting to utilize Google Maps APIs to create a basic autocomplete feature for a "Place" input box within an Angular routing setup. Following Google's developer instructions, in the <head> of my main template, I've in ...

Launching a URL in a pop-up window with customized title and address bar

I am seeking to implement a feature similar to the following: <a href="post/23">post 23</a> When a user clicks on this element, I want a popup div to fade in and load the HTML from page post/23 into it. Additionally, I would like the title an ...

Unable to refresh changing list of checkboxes

Seeking assistance: How can I refresh the drop-down list on the "Remove Locations" page? The list is populated from localstorage.city. To refresh, click on 'Open Panel' and then select Remove Locations. You will see a list of cities that were ad ...