Home > Software design >  How can I get data from another Vue file?
How can I get data from another Vue file?

Time:06-17

As the code show below, A.vue file has element data return some number values

<template></template>
<script>
  export default {
     data(){
       return{
         element: [
           {
             number:'11'
           }
           {
             number:'22'
           } 
         ]
       }
     }
  }
</script>

Now I want to get element.length from A.vue to B.vue. Is there a way to do that? I saw a solution with button click but i dont want to use button to pass data.

B.vue file

<template>
  <div>I want to get element.length here</div>
</template>

CodePudding user response:

If it's possible, just pass the data as a prop from B to A, this way you can implement any logic on the data. If it's not, you should use vuex for data storage, so any component can access it.

CodePudding user response:

You can simply achieve it by passing prop (which contains the length of the element array) from A.vue component to B.vue component. Here is the live demo :

Vue.component('bcomponent', {
  // declare the props
  props: ['length'],
  // just like data, the prop can be used inside templates
  // and is also made available in the vm as this.message
  template: '<div>Element length: {{ length }}</div>',
});

var app = new Vue({
  el: '#app',
  data: {
    element: [{
      number: '11'
    }, {
      number: '22'
    }]
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!-- Component A -->
<div id="app">
  <BComponent :length="element.length">
  </BComponent>
</div>

  • Related