0
votes

I'm quite new with VueJS. I'm working on a new project with VueCLI3 & VuetifyJS.

I'm trying to create a reusable components based on VuetifyJS components and would like to make things easier by passing multiple props in a separate file to render them at once in my new component files. I found this article that explains a technique to achieve such thing.

https://alligator.io/vuejs/passing-multiple-properties/

Every time I need to render them I must import my seperate file.

component1.vue

<template>
  <v-btn v-bind='buttonProps'>
    Button 1
  </v-btn>
</template>

<script>
  import { buttonProps } from './props.js';

  export default {
    data: () => ({ buttonProps })
  }
</script>

component2.vue

<template>
  <v-btn v-bind='buttonProps'>
    Button 2
  </v-btn>
</template>

<script>
  import { buttonProps } from './props.js';

  export default {
    data: () => ({ buttonProps })
  }
</script>

Is there any way to register the file globally so it allows me to use it anywhere in the app like this?

props.js

export const buttonProps = {
  color: 'primary',
  small: true,
  outline: true,
  block: true,
  ripple: true,
  href: 'https://alligator.io'
}

main.js

import Props from 'props.js';

component3.vue

<template>
  <v-btn v-bind='buttonProps'>
    Button 3
  </v-btn>
</template>

<script>
  ... // no import needed
</script>
2

2 Answers

2
votes

You can use a mixin and register that mixin globally.

buttonPropsMixin

export default {
  data() {
    return {
      buttonProps: {
        color: 'primary',
        small: true,
        outline: true,
        block: true,
        ripple: true,
        href: 'https://alligator.io'
      }
    }
  }
}

main.js

import buttonPropsMixin from '...';

Vue.mixin(buttonPropsMixin)

Note That each vue component has its own buttonProps, so if you change in one component the color it will not affect the other components!
If you want buttonProps to have the same state across all your components you can go the vuex way as Igor mentioned and use it with an mixin where you define the mapGetters in that mixin.

0
votes

If data in props.js doesn't need to be reactive and all the components are children of some root component you could do this:

main.js:

import buttonProps from 'props.js';

new Vue({
  el: rootComponentElement,
  buttonProps: buttonProps,
  render: h => h(rootComponent)
})

component.vue:

<template>
  <v-btn v-bind='$root.$options.buttonProps'>
    Button 3
  </v-btn>
</template>

<script>
  ... // no import needed
</script>

Otherwise I would advice you to use Vuex or use the global bus method described here.