Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change data value from one component to another component in Vue Js?

I am new in Vue Js. So, I am facing a problem to changes data value from another component.

I have a component A:

<template>
   <div id="app">
      <p v-on:click="test ()">Something</p>
   </div>
</template>

import B from '../components/B.vue';
export default {
    components: {
        B
    },
    methods: {
        test: function() {
            B.data().myData = 124
            B.data().isActive = true
            console.log(B.data().myData);
            console.log(B.data().isActive);
        }
    }
}

Component B:

export default {
    data() {
        return {
            myData: 123,
            isActive: false

        }
    }

}

It still component B data. But it cannot be affected component B data. I want to data changes of component B from component A. How can I do that?

Please explain me in details. I have seen vue js props attribute but I don't understand.

like image 366
Sukanta Bala Avatar asked Oct 05 '17 10:10

Sukanta Bala


People also ask

How do you transfer data from one component to another?

For passing the data from the child component to the parent component, we have to create a callback function in the parent component and then pass the callback function to the child component as a prop. This callback function will retrieve the data from the child component.

Can we modify props in Vue?

Note: Props are read-only, which means the child component cannot modify them because the data is owned by the parent component and is only passed down to the child component to read it.


2 Answers

You're looking for Vuex.

It's the centralized store for all the data in your applications.

Take a look at their documentation, it should be pretty straightforward.

like image 190
mutantkeyboard Avatar answered Sep 28 '22 17:09

mutantkeyboard


You can pass down props to the component B. These props can be updated by the parent component. You can think of B as a stupid component that just renders what the parent tells it to rendern. Example:

// Component A
<template>
   <div id="app">
      <p v-on:click="test ()">Something</p>
      <b data="myData" isActive="myIsActive"></b>
   </div>
</template>

<script>
import B from '../components/B.vue';
export default {
  components: {
    B
  },
  data() {
    return {
      myData: 0,
      myIsActive: false,
    };
  },
  methods: {
    test: function() {
      this.myData = 123
      this.myIsActive = true
    }
  }
}
</script>

// Component B
<template>
  <div>{{ data }}{{ isActive }}</div>
</template>

<script>
export default {
  props: {
    data: Number,
    isActive: Boolean
};
</script>
like image 29
truefalse10 Avatar answered Sep 28 '22 17:09

truefalse10