It's Siddiqi
It's Siddiqi

Reputation: 125

Make data and methods reusable in Vue js

Let say i have a script like this in vue

<script>
export default {
  name: "BaseCardAnnotationOption",
  data() {
    return {
      includeAnnotations1: false,
      embedIntoImage: null,
      burnIntoImage: null,
      burnReduction1: false,
      maintainColor1: false,
      annotationOption1: null
    };
  },
  methods: {
    deselectDisabled() {
      return this.includeAnnotations1 === false
        ? ((this.annotationOption1 = null), (this.maintainColor1 = false))
        : ((this.annotationOption1 = 0), (this.maintainColor1 = false));
    }
  }
};
</script>

And i am using the data variable and methods in like 4 or 5 other places . Is there a way i could put all these in a new file and just call these from a component when required . Thanks

Upvotes: 2

Views: 628

Answers (2)

thidzz
thidzz

Reputation: 303

Just an addition to Boussadjra Brahim response, if you`re using Vue 3, you can import your functions inside a "script setup" all over your code.

Inside a file like '../module.js' or something else you prefer:

export function deselectDisabled() {

// Here you will need to modify and adapt your function to use callbacks. 

}

Then you can just import it and use it like:

<script setup>
import { deselectDisabled } from './module.js
// Now you can use your function all over your vue file.

...

</script>

It is new a "syntactic sugar" vue 3 is implementing and it is REALLY helpful for big projects. You can see more about this here: https://v3.vuejs.org/api/sfc-script-setup.html

Upvotes: 0

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You could use mixins to define some options and reuse them across your components, create a file called someMixins.js with following content :


export default const someMixins={
data() {
    return {
      includeAnnotations1: false,
      embedIntoImage: null,
      burnIntoImage: null,
      burnReduction1: false,
      maintainColor1: false,
      annotationOption1: null
    };
  },
  methods: {
    deselectDisabled() {
      return this.includeAnnotations1 === false
        ? ((this.annotationOption1 = null), (this.maintainColor1 = false))
        : ((this.annotationOption1 = 0), (this.maintainColor1 = false));
    }
  }

}

then import it inside the component and use as follows :

<script>
import someMixins from 'path/to/someMixins.js'
export default {
  name: "BaseCardAnnotationOption",
  mixins:[someMixins]
}

Upvotes: 3

Related Questions