[Vuejs]-How to pass data Between vue single file component

0👍

You might be looking for Vuex which is a vue data management plugin that all your components will have access to

import Vue from 'vue'
import Vuex from 'vue'

Vue.use(Vuex)

const store = new Vuex.Store({
  // data will be stored here
  state: {
    apiData: null,
  },
  mutations: {
   // you call this mutation to add data  
    apiData(state) {
      state.apiData = apiData
    }
  },
  getters: {
    // a getter for the data
    apiData(state) {
      retrun state.apiData
    }
  }
})

// new Vue({...,store})

you can add data to the store immediately after the fetching with :

this.$store.commit('apiData',yourdatahere)

and then access/get it on any component with :

this.$store.getters.apiData

you can read more about Vuex

0👍

There are numerous ways, to name a few

  1. one file for get data from api don’t need to be a vue instance. You may want to add more hooks.
// ApiService.ts
export const ApiService = { getData: () => {/**/} }

// src/components/Filters.vue
...
<script lang="ts">
  import Vue from 'vue';
  import {ApiService} from '@/.../ApiService'

  export default {
    data: () => ({
      filters: []
    }),
    created() {
      ApiService.getData().then(data => this.filters = data)
    }
  };
</script>

  1. You can certainly make a Vue instance to provide data, to make it reactive and component independent from data logic. For example:
// ApiService.ts
const ApiService = new Vue({
  data: () => ({
    filters: []
  }),
  created() {
    request().then(data => this.filters = data)
  }
})

// src/components/Filters.vue
...
<script lang="ts">
  import Vue from 'vue';
  import {ApiService} from '@/.../ApiService'

  export default {
    computed: {
        filters() {
          return ApiService.filters
        }
    }

  };
</script>

Leave a comment