Create a global sort method inside a .js file required inside main.js. Inside Component.vue :click call sort on a computed property. Is this possible?

Viewed 106

main.js

import Component from '/Component';
require('/file.js');
const app = new Vue({
   el: '#app',
   components: {
      Component
   }
});

file.js

sortComputedArray = function(field_name, direction, computedArray){
    computedArray.sort() //example instead of lodash.js
}

Component.vue

<template>
   <button :click="sortComputedArray('id', 'asc', computedArray)"></button>
</template>
export default {
   computed: {
       computedArray(){
          return this.new_array;
       }
   },
   data(){
      return{
        new_array: [associativeArrayWithIds]
      }
   }
}

This is the idea, but I am not sure how to declare that method in the .js file and how to pass the computed property array in order to use this method as a global filter in the future. Any ideas?

1 Answers

There are some issues with your code:

  • The event handler shorthand is @ like @click, not : like :click
  • You are trying to sort a computed without cloning it first, which would mutate it. Computeds are automatically calculated based on reactive data and should not be mutated.

I won't address those since your question is asking about importing/exporting. You can import the helper function directly into any component. But first you have to export it using es6 module syntax from file.js:

export const sortComputedArray = function(field_name, direction, computedArray){
    computedArray.sort() //example instead of lodash.js
}

Now it's ready to be imported in Component.vue. You can use it anywhere in the component as sortComputedArray:

<template>
   <button @click="sort"></button>
</template>

<script>
import { sortComputedArray } from './file.js';

export default {
  ...
  methods: {
    sort() {
      // This is called from the button, and it sorts the data array
      sortComputedArray('id', 'asc', this.new_array);
    }
  }
}
</script>
Related