Sev M
Sev M

Reputation: 38

Vue3 - Composition Function vs. import { functionObject } from 'module'

So I just read through the new Composition API RFC (link). Here they compare multiple methods to reuse code across components. Therein the import from module method is not included. I guess that's because they are talking about VueJS strictly and for comparison purposes.

In the example they state a search algorithm. This I used in one of my projects. First I made a module which exports the function as an object:

##search_module.js

let fnc = {
    perform_simple_search: function (str, arr) {
        let result = [];

        arr.forEach(value => {
            if (value.toString().toLocaleUpperCase().includes(str.toLocaleUpperCase()) || value.toString().toLocaleLowerCase().includes(str.toLocaleLowerCase())) {
                if (result.indexOf(value) === -1) {
                    result.push(value)
                }
            }
        });
    }
}

module.exports = {
    perform_simple_search: fnc.perform_simple_search
};

And where I needed the function in a component I just imported it like so:

import {perform_simple_search} from "../search_module";

And here is now my Question:

Why use a composition Function if I can just import a function from a module?

Upvotes: 2

Views: 1249

Answers (1)

ajobi
ajobi

Reputation: 3116

It's not about that.

See - your perform_simple_search function truly is a piece of logic that can be shared throughout the project. The problem is it can never encapsulate stateful logic. And that is what will be possible with the composition API.

You will be able to define pieces of state and methods inside these functions and reuse this stateful logic in your components. Imagine extracting this piece of stateful logic into a function which you will import in different components to give them counting ability:

setup() {
  const state = reactive({
    count: 0
  })

  function increment() {
    state.count++
  }

  return {
    state,
    increment
  }
}

This was already possible with mixins / scoped slots, but these methods had their problems:

https://www.vuemastery.com/courses/vue-3-essentials/why-the-composition-api/

Upvotes: 2

Related Questions