Get a value from antoher .vue file


#1

Hi, I’d like to get a value from another vue file.
Imagine i have:

File where i want the value (main.vue):

<template>
    <p>{{show}}</p>
</template>

<script>
import value from "./value/value.vue";

</script>

File where I’ll get the value (value.vue):

<template>
    <button @click="show=!show">BUTTON</button>
</template>

<script>
export default{
    data() {
      return {
       show: ""
    };
}
</script>

So I’d like that every time I press the button, the value show switches. And on main.vue I want to see whether show is true or false.

I’ve tried with $emit and $on, but I don’t really undersantd.

Can someone explain me how to do that?


#2

Have a look at state management.


#3

To put it easily,

main.vue is parent component and value.vue is child component .

The way to pass events from the child component to the parent component is to notify the parent component via emit () on the events that occur in the child component.

main.vue (parent component)

<template>
   <!--Register the function to be called at the event("testEventName") to be delivered from the child component -->
   <v-value @testEventName="parentDoSomething"></v-value>
   {{ childFlag }}
</template>

<script>
import Value from "./value/value.vue";

~~skip ~~

components: {
  "v-value": Value
},
data() {
  childFlag: false
},
methods {
  // This function is called when child component's event is triggered 
  parentDoSomething: function(flag) {
    console.log(flag)
    this.childFlag = flag;
  }
}
</script>

value.vue

<template>
    <button @click="childFunction">BUTTON</button>
</template>

<script>
export default{
    data() {
      return {
       show: ""
    },
   methods: {
      // click this button => show flag is toggled and transfer event to parent component 
      childFunction: funciton()  {
         this.show = !this.show
         // "testEventName" is just event name 
         this.$emit("testEventName", this.show);
      }
   }
}
</script>

In this way, the parent-child event is delivered.
I hope my answer will help. :slight_smile:


#4

Get it!!

Many thaanks!!!