0

i have an array of products

const products = [
 { id: 1, productname: "64GB Phone", qty: 1, price: 33070, image: 
 require('../assets/phone.png') },

i have added this into 3 files is their any way i can declare this in one file & call it in 3 files without writing the whole array ?

1
  • as the labels suggest, you can create store.js for global data states or using Vuex. Commented Jun 10, 2020 at 9:18

3 Answers 3

1

One valid pattern is to use mixins:

import { reusableMixin as products } from "@/mixins/reusableMixin"
const component = {
  mixins: [
    products
  ],
  data(){
    return {...}
  },
  ...
}
___________________________

export const reusableMixin = {
  data(){
    return {
      products: [...] 
    }
  }
  // or when piping 
  computed:{
    products_piped: {
      get(){
        return getFromAnywhereSync()
      },
      set(val){
        setSomeWhere(val)
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to make changes on this array and all pages get that change then import is not the correct way because if you change it in one component the other component will not take that change. if you want something like this you have to add it in store (vuex) tell us exacly what do you need it for to help you ^^

1 Comment

How to use vuex ? to store data in a vue app ?
0

You can set a prototype in your main.js file as follows:

Vue.prototype.$products = { 
  id: 1, productname: "64GB Phone", qty: 1, price: 33070, image: 
  require('../assets/phone.png') 
};

Then, use this.$products within your Vue components.

(You have an erroneous open square bracket here: const products = [ in your example)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.