How do child components in Vue.js impact the state of their parent?

According to the information on vuejs.org:

The two-way binding in Vue.js will synchronize any changes made to a child component's 'msg' property back to the parent component's 'parentMsg' property. You can check out more details about this here.


I'm somewhat puzzled about how I can modify a child component's property in a way that these changes will be reflected back in its parent.


router

// Setting up router rules.
router.map({
    '/categories': {
        // The List.vue
        component: CategoryList,

        subRoutes: {
            // ... additional rules here ...
            '/add': {
                // The DetailAdd.vue
                component: CategoryDetailAdd
            }
        }
    }
});

List.vue (the parent)

<template>

    <tab v-bind:tabs="tabs" :active="active"></tab>

    <div class="col-lg-12">
        <router-view :categories="categories"></router-view>
    </div>

</template>
<script>

    var Tab = require('../common/Tab.vue');
    export default{
        components:{
            tab: Tab
        },
        data() {
            return {
                categories: [],
                tabs: [],
                active: '1'
            };
        },
        ready() {
            this.$http.get('/categories').then((response) => {
                // success
                this.$set('categories', response.data.categories);
                this.$set('tabs', response.data.tabs);
                this.$set('active', response.data.active);
        }, (response) => {
                // error handling
            })
        }
    }
</script>

DetailAdd.vue (the child)

<template>
    <form class="form-horizontal" method="post" action="/categories/add">

        <div class="form-group">
            <label for="name" class="col-md-2 control-label">name</label>
            <div class="col-md-10">
                <input id="name" type="text" class="form-control" name="name" value="" />
            </div>
        </div>

        <div class="form-group">
            <label for="category_id" class="col-md-2 control-label">superiror</label>

            <formselect></formselect>
        </div>

        <div class="form-group">
            <label for="sort_order" class="col-md-2 control-label">sort</label>
            <div class="col-md-10">
                <input id="name" type="text" class="form-control" name="sort_order" value="" />
            </div>
        </div>

        <formbutton></formbutton>
    </form>
</template>

<script>
    var FormSelect = require('../common/FormSelect.vue');
    var FormButton = require('../common/FormButton.vue');

    export default{
        components: {
            formselect: FormSelect,
            formbutton: FormButton
        }
    }

    $(function() {
        $('.nav-tabs').on('ready', function() {
            $('.nav-tabs li').attr('class', '');
            $('.nav-tabs li:last').attr('class', 'active');
        });
    });
</script>

All I want to do is update the active property in the parent component (List.vue). Is there a recommended approach to achieve this?

Thank you all for your assistance!

Answer №1

The concept of two-way binding functions as you would expect: changes made to a property in the parent reflect in the children, and vice versa. An illustration of this can be seen here: https://jsfiddle.net/u0mmcyhk/1/, where the children can alter the state of the parent. If you eliminate .sync from the parent template, this functionality ceases.

It's worth mentioning that .sync will become obsolete in version 2.0, giving preference to communication methods such as broadcast, dispatch, or utilizing state management tools like vuex.

For further details, refer to: https://vuejs.org/api/#v-bind

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

Is it possible that React.createElement does not accept objects as valid react children?

I am working on a simple text component: import * as React from 'react' interface IProps { level: 't1' | 't2' | 't3', size: 's' | 'm' | 'l' | 'xl' | 'xxl', sub ...

Issues encountered when attempting to parse a JSON object using jQuery

My PHP file is set up like this: <?php include('connection.inc.php'); ?> <?php header("Content-type: application/json"); ?> <?php $sth = mysql_query("select * from ios_appointments a join ios_worker w join ios_partners p wher ...

What is the best way to prevent a directory from being included in the Webpack bundle?

Issue: Despite configuring my Webpack settings in webpack.config.js to exclude files from the ./src/Portfolio directory, all files are being bundled by Webpack. Code Snippet: Webpack.config.js const path = require('path'); module.exports = { ...

Difficulty in jQuery's clone() function: cloning an input element without its value

I have successfully implemented jquery's .clone() method, but I'm facing an issue where the value of the previous input field is also getting cloned along with it. How can I prevent this from happening? Below is my code snippet: function addrow ...

Launching a Node.js command-line interface to NPM, developed using TypeScript

I'm struggling with deploying my Node CLI tool to NPM. During development and testing, everything works fine. I can even use `npm link` on the repo without any issues. After successfully publishing and downloading the package, the application crashes ...

Build a new shop using a section of data from a JSON database

Let's say I have a JSON store that is set up as shown below var subAccountStore = new Ext.data.JsonStore({ autoLoad: true, proxy: { type:'ajax', url : '/opUI/json/subaccount.action?name="ABC"' }, fields: ['acc ...

When I upload a file using v-file-input, it displays two names

While working with nuxt, I made an interesting discovery. See the pattern here The top name is the file that was uploaded, and the bottom one is the target file name. I plan to remove the bottom name and replace it with the top. This is what I envision: E ...

When used, the jQuery selector returns the PreviousObject rather than the object that was selected initially

I'm currently attempting to add a second menu to my website alongside the top menu. I have multiple menus set up in two bootstrap columns (col-8 and col-4). Initially, when I used jQuery selectors outside of a function, everything worked smoothly. How ...

Experiencing a problem with generating nested elements using JavaScript

I'm looking to customize the default header of a div using a JavaScript function, but the final result of my code is displaying as [object HTMLDivElement]. Here's the code snippet I'm working with: function CustomizeHeader(){ va ...

Utilizing AJAX and PHP POST to dynamically refresh innerHTML content with MySQL data updates

I've been trying to solve this problem for a long time now, and I've reached a point where I can't seem to figure it out. On a page, there are several forms where users input different information that gets submitted to a mySQL database usin ...

Prevent the execution of a post request function depending on the promise result?

When I handle a POST request in express, I am required to retrieve data from a mongoDB cluster and then respond accordingly based on the retrieved response. app.post('/api/persons', (req, res) => { const data = req.body; if (!data.name || ...

Unable to retrieve information from JSON using jQuery's AJAX method

My journey with learning JSON using jQuery has hit a bump in the road. Despite spending two days and going through various tutorials on YouTube and blogs, I'm facing a challenge. The JSON structure presented in the tutorials differs from the one I hav ...

Using jQuery to duplicate a div multiple times when scrolling

I'm looking for a way to continuously duplicate the contents of a div as I scroll, creating the illusion of an infinitely scrolling page. My current markup looks like this and you can also find a working example in this fiddle https://jsfiddle.net/guh ...

Issue: main@HEAD Failed during 'site building' stage: Build script ended with non-zero exit code: 2

11:29:48 AM: build-image version: 3d3c7e8b4321e2c1a54a2c4584fb46ba742b1630 (focal) 11:29:48 AM: buildbot version: 72ed9578274f76ae72cdce4c5312615aeecc32fb 11:29:49 AM: Building without cache 11:29:49 AM: Starting to prepare the repo for build 11:29:49 AM: ...

Alternating row colors using CSS zebra striping after parsing XML with jQuery

After successfully parsing XML data into a table, I encountered an issue with applying zebra stripe styling to the additional rows created through jQuery. Despite my efforts to troubleshoot the problem in my code, I remain perplexed. Below is a snippet of ...

The React route fails to display until clicked upon

Struggling with integrating React Router into my Electron desktop app for navigation. During debugging, I realized that the login component, which doesn't use routers, transitions smoothly to a component with a router. However, this new component fail ...

Enjoy watching a video by simply hovering over the highlighted words

I am looking to implement a function where the video plays when hovering over highlighted words and pauses when the mouse moves away. However, I am currently only able to get the video to autoplay upon hover, not the highlighted words. Any assistance on th ...

Transfer the export to a different file and update all the files that import it accordingly

Is there a way, particularly in Typescript, to seamlessly move an export statement like the one below to an existing file and automatically update all files that import it? export const MyVar = 3; In the case of refactoring using Right Click > Refactor ...

Issue with Vue plugin syntax causing component not to load

I'm facing an issue with a Vue plugin that I have. The code for the plugin is as follows: import _Vue from "vue"; import particles from "./Particles.vue"; const VueParticles = (Vue: typeof _Vue, options: unknown) => { _Vue. ...

The issue with the transition element not functioning properly in the hamburger menu is being encountered while using Tailwind CSS alongside

I am currently working on creating a responsive navigation bar in nuxt3/vue. <template> <nav class="flex justify-between items-center w-[92%] mx-auto gap-4 border border-2 border-black p-2" > <div> <span cla ...