appson
appson

Reputation: 183

How to transfer data between components placed in different views

I have two compoennts placed in one the same view.

@extends('layouts.app') 
@section('content')
<bus></bus>
<bus2></bus2>
@endsection

I want to pass data (name) from one component to other one after clicking button. To do that I' using $emit function.

/// bus component
<template>
    <div>
        <p> Name Bus 1{{name}}</p>
        <input type="button" @click="setName()"  value="s"/>
    </div>
</template>

<script>
export default {
  created() {},
  data: function() {
    return {
      name: "Volvo"
    };
  },
  methods: {
    setName: function(id) {
      this.$root.$emit("sname", this.name);
    }
  },
  props: []
};
</script>



///bus 2 component

<template>
    <div>
        <p> Name bus 2{{name}}</p>

    </div>
</template>

<script>
export default {
  created() {
    this.$root.$on("sname", data => {
      this.name = data;
    });
  },

  data: function() {
    return {
      count: 0,
      name: ""
    };
  },

  methods: {}
};
</script>

Everything works fine. Name is transfered from bus to bus2. The problem exists when I place bus2 in different view - data are not transfered but code is the same. How can I transfer data between components placed in different views

Upvotes: 0

Views: 76

Answers (1)

J&#233;r&#244;me
J&#233;r&#244;me

Reputation: 2056

Try using Vuex to specify your app state, and mutate this when it's necessary.

Vuex states are accessible from every components using this.$store or $store.

Upvotes: 1

Related Questions