2

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

1
  • If you're looking for a centralized store: vuex.vuejs.org Commented Jan 8, 2022 at 10:00

2 Answers 2

3

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]
}

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.