How to share data between components Vue js

2019-08-23 06:26发布

问题:

Hi there I saw posts talking about this, but is not easy for me understand what I have to do to share data between components, I don't want to use event bus so can you tell me how to use props??

Component A:

<template>
  <div>
    <div class="container">

                  <fileForm></fileForm> //<--- THE COMPONENT B      
        </div>
      </div>
</div>
</template>

<script>

export default {

  name: "DashBoard",
  data() {
    return {
      user: {},
    };
  },
  methods: {
    checkIfImLoggedIn() {

      }
    },
    onComplete() {
    },
  },
  mounted() {
    this.checkIfImLoggedIn();
  }
};
</script>

Component B:

<template>
  //...
</template>

<script>
export default {
  name: "FileForm",
  data() {
    return {
      fileExtensions: ["CSV", "EXCEL"],
      sharedData : {}, //<--- for example share this

    };
  },
  methods: {}
};
</script>

回答1:

If you want to share data from the parent to the child you can do:

on component A

<fileForm :something="user"></fileForm>

In component B

props: {
  something: Object
}

If you want to share data from the child to the parent you have to use an event bus or vuex: https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication



回答2:

https://alligator.io/vuejs/component-communication/

You need do do research about component communication their is a lot of way to do it ;)