Kamuran Sönecek
Kamuran Sönecek

Reputation: 3333

How to Two-way Data Binding Between Parents and grandchildren in Vue.js

I faced a problem, I solve it by cookies but I want to solve the problem without cookies. I have a component which called app-header and It has another component which called outmodal. Now, My first Vue instance require component app-header.

var vue = new Vue({
    el : "html",
    data : {
        title       : "Site Title",
        description : "description of page",
        keywords    : "my keywords",
        view        : "home",
        login       : "login"
    },
    components:{
        "app-header" :require("../../components/header"),
        "app-footer" :require("../../components/footer"),
        "home"       :require("../../views/home")
    },
});

code of app-header

var Vue     = require("vue");

Vue.partial("login",require("../../partials/login.html"));
Vue.partial("logged",require("../../partials/logged.html"));

module.exports = {
    template    : require("./template.html"),
    replace     : true,
    components  : {
        outmodal : require("../outmodal")
    },
    props : ['login']
}

code of outmodal

var Vue = require("vue");
Vue.partial("loginModal",require("../../partials/loginModal.html"));

module.exports = {
    template    : require("./template.html"),
    replace     : true,
    props       : ['name'],
    data        : function () {
            return  {
                userLogin : { mail  :   "", password    :   "", remember    :   ""}
            }

    },
    methods : {
        formSubmit : function(e){
                e.preventDefault();
                this.$http.post("http://example.com/auth/login",{ "email": this.userLogin.mail , "password": this.userLogin.password },function(data,status,request){
                    $.cookie("site_token",data.token,{expires : 1})
                }).error(function(data,status,request){

                });

        }
    }, ready  : function(){
        console.log("it works")
    }
}

In outmodal component I connect the API and I check the login, If login will be succesfull, I want to change value of login variable in my Vue instance. I use web pack to build all requires. So I don't know how can I data binding between these files.

How can I solve It? I

Upvotes: 36

Views: 57324

Answers (4)

SanBen
SanBen

Reputation: 2798

There are several ways of doing it, and some are mentioned in other answers:

  1. Use props on components

  2. Use v-model attribute

  3. Use the sync modifier (for Vue 2.0)

  4. Use v-model arguments (for Vue 3.0)

  5. Use Pinia

Here are some details to the methods that are available:

1.) Use props on components

Props should ideally only be used to pass data down into a component and events should pass data back up. This is the way the system was intended. (Use either v-model or sync modifier as "shorthands")

Props and events are easy to use and are the ideal way to solve most common problems.

Using props for two-way binding is not usually advised but possible, by passing an object or array you can change a property of that object and it will be observed in both child and parent without Vue printing a warning in the console.

Because of how Vue observes changes all properties need to be available on an object or they will not be reactive. If any properties are added after Vue has finished making them observable 'set' will have to be used.

 //Normal usage
 Vue.set(aVariable, 'aNewProp', 42);
 //This is how to use it in Nuxt
 this.$set(this.historyEntry, 'date', new Date());

The object will be reactive for both component and the parent:

I you pass an object/array as a prop, it's two-way syncing automatically - change data in the child, it is changed in the parent.

If you pass simple values (strings, numbers) via props, you have to explicitly use the .sync modifier

As quoted from --> https://stackoverflow.com/a/35723888/1087372

2.) Use v-model attribute

The v-model attribute is syntactic sugar that enables easy two-way binding between parent and child. It does the same thing as the sync modifier does only it uses a specific prop and a specific event for the binding

This:

 <input v-model="searchText">

is the same as this:

 <input
   v-bind:value="searchText"
   v-on:input="searchText = $event.target.value"
 >

Where the prop must be value and the event must be input

3.) Use the sync modifier (for Vue 2.0)

The sync modifier is also syntactic sugar and does the same as v-model, just that the prop and event names are set by whatever is being used.

In the parent it can be used as follows:

 <text-document v-bind:title.sync="doc.title"></text-document>

From the child an event can be emitted to notify the parent of any changes:

 this.$emit('update:title', newTitle)

4.) Use v-model arguments (for Vue 3.0)

In Vue 3.x the sync modifier was removed.

Instead you can use v-model arguments which solve the same problem

 <ChildComponent v-model:title="pageTitle" />

<!-- would be shorthand for: -->

<ChildComponent :title="pageTitle" @update:title="pageTitle = $event" />

5.) Use Pinia (or Vuex)

As of now Pinia is the official recommended state manager/data store

Pinia is a store library for Vue, it allows you to share a state across components/pages.

By using the Pinia store it is easier to see the flow of data mutations and they are explicitly defined. By using the vue developer tools it is easy to debug and rollback changes that were made.

This approach needs a bit more boilerplate, but if used throughout a project it becomes a much cleaner way to define how changes are made and from where.

Take a look at their getting started section


**In case of legacy projects** :

If your project already uses Vuex, you can keep on using it.

Vuex 3 and 4 will still be maintained. However, it's unlikely to add new functionalities to it. Vuex and Pinia can be installed in the same project. If you're migrating existing Vuex app to Pinia, it might be a suitable option. However, if you're planning to start a new project, we highly recommend using Pinia instead.

Upvotes: 22

MartianMartian
MartianMartian

Reputation: 1849

i found this one to be more accurate. https://v2.vuejs.org/v2/guide/components.html#sync-Modifier only in 2.3.0+ tho. and honestly it's still not good enough. should simply be a easy option for 'two-way' data binding. so none of these options is good.

try using vuex instead. they have more options for such purpose. https://vuex.vuejs.org/en/state.html

Upvotes: 3

Fenix
Fenix

Reputation: 2391

I would prefer event-driven updates as recommended in the documentation. However, I was limited by the existing ("third-party") component already using props and $emit. This component is my grandchild. The following is my solution (passing value through child using props, sync and computed value with $emit.

Comments are welcome.

Value can be modified in parent and grandchild without error:

Grandchild (simplified third-party component):

<template>
  <div v-show="value">{{ value}}</div>
  <button @click="closeBox">Close</button>
</template>

<script>
export default {
  props: {
    value: null
  },
  methods: {
    closeBox() {
      this.$emit('update:value', null);
    }
  }
}
</script>

Child:

<template>
  <grandchild-component :value.sync="passedValue" />
</template>

<script>
export default {
  props: {
    value: null
  },
  computed: {
    passedValue: {
      get() {
        return this.value;
      },
      set(newVal) {
        this.$emit('update:value', newVal);
      }
    }
  }
}
</script>

Parent:

<template>
  <child-component :value.sync="value" />
</template>
<script>
export default {
  data() {
    return {
      value: null,
    }
  },
  // ... e.g. method setting/modifying the value
}
</script>

Upvotes: 0

Related Questions