Vue 3: Exploring the Composition API - A Guide to Invoking Methods in Component Instances

In my experience with Vue 2, I approached it in the following way:

import Component from '@/components/Component.vue';

    const VueComponent = {
      install(Vue, settings = {}) {
        const Constructor = Vue.extend(Component);
        const ComponentContainer = new Constructor();
    
        ComponentContainer._props = Object.assign(ComponentContainer._props, settings);
        const vm = ComponentContainer.$mount();
        document.querySelector('body').appendChild(vm.$el);
       }
    }

After that, I could easily call any component method like this:

ComponentContainer.add();

Now, as I'm transitioning to creating components using Vue 3, TypeScript, and Composition API, my approach is slightly different:

import { App, createApp, Component } from 'vue';
import ComponentName from './components/ComponentName.vue';

const VueComponentName: Component = {
  install(Vue: App, settings = {}) {
    const ComponentContainer = createApp(ComponentName);
    ComponentContainer._component.props = Object.assign(ComponentContainer._component.props, settings);

    const wrapper = document.createElement('div');
    const vm = ComponentContainer.mount(wrapper);
    document.body.appendChild(vm.$el);
  },
};

Within the component itself, I define a method called add:

export default defineComponent({
  name: 'ComponentName',
  setup(props, {}) {
    const add = (status) => {
      console.log('test')
    };

    return { add };
  },
});
</script>

However, when trying to use this component method from the plugin, such as ComponentContainer.add();, I realize that the component instance does not have this method. What am I doing wrong?

Answer №1

It seems like you're diving deep into some complex concepts for a vue component, but not to worry!

In Vue 3, anything declared within the setup method remains private to the component by default. If you need external access to certain properties, you can explicitly declare them using the defineExpose composable.

export default {
  setup() {
    function add() {...}

    defineExpose({ add })

    return { add }
  }
}

You can also achieve similar functionality when using the options API with expose

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The unexpected error occurs when using JSON.parse() with the message 'Unexpected end of JSON input'

The output produced by console.log(d) is in hexadecimal code: <Buffer 7b 22 73 75 63 63 65 73 73 22 3a 74 72 75 65 2c 22 64 61 74 61 22 3a 7b 22 73 75 6d 6d 61 72 79 22 3a 7b 22 74 6f 74 61 6c 22 3a 31 39 39 32 35 36 30 ... 293 more bytes> <Buff ...

How can a Vue component interact with a JavaScript method?

Within my main.js file, I have configured Vue as follows: window.Vue = require('vue'); Vue.component('my-component', require('./components/MyComponent.vue')); const app = new Vue({ el: '#app', }); Additionall ...

Oh no, the dreaded encounter with Gulp, Vue, Webpack, Babel causing an unexpected token import SyntaxError!

I have been struggling all day to make this work, but I haven't had any luck. If someone could provide some insight, it would be greatly appreciated. My goal is to set up an environment for working with ES6 files and Vue using Webpack. I have instal ...

Style your Checkbox Button with the Checkbox component from Element Plus

Currently, I am utilizing Vue 3 along with the Element Plus library. My goal is to modify the hover, active, and select colors of the Checkbox Button that I have implemented. Unfortunately, my attempts to do so have not been successful. I essentially copie ...

Choosing to selectively trigger a function using TypeWriter

I have successfully implemented TypeWriter to generate TypeScript classes from my C# models. The template I am currently using is shown below: ${ using Typewriter.Extensions.Types; Template(Settings settings) { settings.IncludeProject ...

Nested V-If statements inside of a double V-For loop

As a newcomer to Vue, I am experimenting with running an IF statement inside two v-fors. My goal is to compare a value from one array of objects to a value of another array of objects and if true, render the value from the second array of objects. Here is ...

Switch button - reveal/conceal details

I am looking for assistance in toggling the visibility of information when clicking on an arrow icon. I have attempted to use JavaScript, but it was unsuccessful. My goal is to hide the information below by clicking on the downward-facing arrow image , an ...

Guide to showcasing a story on Storybook

Overview I recently incorporated Storybook into my Nuxt.js application. I managed to get Storybook up and running successfully. I created index.vue and index.stories.ts. However, I'm facing an issue where Storybook is not displaying any Stories. ...

The system encountered an internal server error when attempting to locate and import the file

I seem to be having trouble loading components. I'm not sure what I missed connecting somewhere. <template> <MainLayout></MainLayout> </template> <script setup> import MainLayout from "../layouts/MainLayout.vue&qu ...

Encountering a Typescript error with Next-Auth providers

I've been struggling to integrate Next-Auth with Typescript and an OAuth provider like Auth0. Despite following the documentation, I encountered a problem that persists even after watching numerous tutorials and mimicking their steps verbatim. Below i ...

What is the Purpose of Including the Reducer Name in the NGRX State Tree?

I've encountered an issue while using NGRX to store a simple object. When the object is added to the state tree, the reducer's name is also included, causing problems when I try to strongly type my selector and subscribe to it. Here is the code ...

Is it still necessary to use the ES6 module loader now that TypeScript 1.5 has integrated ES6 modules?

Can the separate ES6 module loader still required for the Angular 2 demo now that TypeScript 1.5 includes this syntax? Any suggestions on how to implement it without the additional loader? <head> <title>Angular 2 Quickstart</title> ...

Passing data from an API in Vue.js to a different page

I'm a beginner with Vue Js and I'm looking for guidance on how to send data between two components. Currently, I am working on a Vue app that fetches a list of users from an API and displays them. My goal is to transfer data between these compone ...

"If the property is not undefined, use a conditional type to retrieve the numerical index from it, otherwise display a message indicating that there is

Here is a snippet of code I am working with: type Numbers = [3,65,2,7,3,99,23,555]; interface Options { options?: Numbers; } type FilterOption = Options['options'] extends undefined ? undefined : Options['options'][number]; I am tr ...

Specialized Character Formats in TypeScript

In my quest to enhance the clarity in distinguishing different types of strings within my program - such as absolute paths and relative paths, I am seeking a solution that ensures functions can only take or return specific types without errors. Consider t ...

Errors in Visual Studio regarding typescript are often not found by tsc and eslint, causing frustration for developers

Today, after restarting my computer and launching visual studio code, I encountered an unfamiliar error that I've never seen before: https://i.sstatic.net/z1vw5.png I haven't made any changes to my project's code (confirmed by running git ...

Is Typescript capable of converting ES6 code to ES5 during transpilation?

Currently, I'm in the process of developing an application utilizing Angular 2 and TypeScript. My goal is to incorporate a JavaScript method, specifically 'filter' for arrays, that is compatible with IE 11+, Chrome 45+, and other similar bro ...

The function 'appendChild' is not recognized on the type 'unknown'.ts(2339)

I'm encountering an issue while trying to integrate the Utterances component into my articles. Upon attempting to build the site, I receive the following error message: "Property 'appendChild' does not exist on type 'unknown' ...

Beating the API call system: Utilizing the RxJS skip operator

Currently, I am attempting to utilize the skip operator in RxJS to skip the initial API call. However, despite my efforts, I have not been successful in achieving this. const source = of('a', 'b', 'c', 'd', 'e&a ...

Learn how to effectively capture errors throughout your Vue JS application and showcase them within a prominent top level component for easier

My Vue setup includes a top level AppLayout component with Navigation Menu and router-view components. It also uses v-if to optionally display an ErrorDisplay component based on the err state variable in the Vuex store. This is my current setup, but I bel ...