Is it possible to retrieve Vue app attributes within a Vue 3 method defined in the composition API?

I'm struggling to understand the extent to which Vue 3 composition API methods can access the attributes of a Vue app, including data.

Check out this jsfiddle, which is based on a fork of the Vue demo fiddle.

With a method defined in the options API, it's easy to retrieve values from data.

However, when using a method defined in the composition API, it seems like data and the app instance are out of reach. There's no this, as previously mentioned. It feels like the composition and options API parts are isolated from each other.

testopt, defined in the options API, has access to data and references returned by setup.

"Yo! from options API: Hello Vue!"
"this.msg2: Hello2"

testcompo, defined in the composition API, cannot see data, but can see references returned by setup.

"Yo! from composition API: this: undefined:"
"context: [object Object]: "
"context.data: undefined:"
"context.$data: undefined:"
"context.attrs: [object Object]: "
"context.attrs.data: undefined:"
"arg2: undefined:"
"msg2: Hello2"
"Yes, I know how setup and refs work. counter is now: 4"

Answer №1

Learn how to utilize getCurrentInstance for accessing the options API:

const { createApp, ref, getCurrentInstance } = Vue
createApp({
  data() {
    return {
      message: 'Hello Vue!'
    },
  setup(props, context){
    const msg2 = ref("Hello2");    
    const vm = getCurrentInstance()
    function testcompo (evt, arg2) {
       console.clear();
       console.log("Hey there! from composition API: " + msg2.value);
       console.log("message: " + vm.data.message);
    };
    return { testcompo, msg2 }
  },
  methods : {
     testopt(evt){
       console.clear();
       console.log("Hey there! from options API: " + this.message)
       console.log("msg2: " + this.msg2);
     }
  }
}).mount('#app')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="app">
  <div>{{ message }}</div>
  <button @click="testopt">
  Test option API here
  </button>
  <button @click="testcompo">
  Test composition API here
  </button>
</div>

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

Error encountered while integrating AngularJS date picker

I am facing an issue while trying to set up the AngularJS date picker from this link. I am getting an error message that I don't quite understand. Could it be due to a missing library file or just syntax errors? var myApp = angular.module('myA ...

Encountered a loading error while attempting to retrieve a JSON file from the GitHub repository

While delving into learning JSON and AJAX, I encountered a challenge when trying to load a simple JSON file from a repository on GitHub. To set up a local server, I am utilizing browser sync along with the following code snippet: var request = new XMLHtt ...

Vue.js behaving abnormally due to certain circumstances

Currently, I am working on a vue application where I encountered some errors related to script execution on certain websites. By implementing the following code snippet, the issue is resolved: if ( window.location.href === 'chrome-extension:// ...

The first three AJAX requests are successful, but the fourth one fails to reach the PHP script

I am currently working on cascaded selects (a total of 4) that retrieve data from a database. To populate them, I use SQL queries based on the selection made in the previous select element. To establish communication between the select element and the subs ...

What is the method for deactivating the voting button for a product review when the review's ID is present in local storage?

Managing reviews with user voting in a React app can be challenging. Each review can be deemed helpful or not, and each product may have multiple reviews. When a user votes on a review, the corresponding button should be disabled. I store the clicked revie ...

Top Tips for Managing Parameter Updates in Vue Router

Utilizing Vue Router with routes such as /foo/:val requires adding a watcher to respond to parameter changes. This can lead to repetitive code in all views containing parameters in the URL. An example of this situation is illustrated below: export defaul ...

I am having trouble combining my streams with es.merge

Here is the gulp task that I am working on: var es = require('event-stream'), concat = require('gulp-concat'), templateCache = require('gulp-angular-templatecache'); var scripts = gulp.src(paths.js + '/**/*.js&a ...

Invoking a .js file within an UpdatePanel from the CodeBehind

I have been dedicating my time to self-teach ASP.NET and JavaScript for a project, and I've hit a roadblock that has consumed dozens of hours. After discovering a fantastic drag-and-drop JavaScript list online, I copied the provided source code and o ...

Is it possible to implement pagination using 'useSWR' in combination with the contentful-client?

I am currently working on implementing pagination in a Next.js project using the useSWR hook. My approach seems to be functioning correctly, but I have a concern about caching due to the key parameter not being a unique string as recommended in the documen ...

Implement Placeholder feature in ng2-ckeditor with the combination of Typescript and Angular 2.0

I am encountering an issue while trying to add the placeholder plugin to the CKEditor toolbar. When I include extraPlugins:'placeholder' in the CKEditor configuration, I receive the following error - Error: [CKEDITOR.resourceManager.load] Resou ...

Vue component utilizing named slots

Can this be done? Here is an example of what I have: <template> <my-layout> <template #header> Some header html goes here </template> Body html here </my-layout> </template> <scri ...

I encounter an error message stating "Cannot read property 'push' of undefined" when trying to add an item to a property within an interface

I have a model defined like this : export interface AddAlbumeModel { name: string; gener: string; signer: string; albumeProfile:any; albumPoster:any; tracks:TrackMode[]; } export interface TrackMode { trackNumber: number; ...

MongoDB: total value of combined fields

Our records show: {a: 1} {a: 5} {a: 3} Is there a way to aggregate this data and calculate the current sum? {a: 1, cs: 1} {a: 5, cs: 6} {a: 3, cs: 9} ...

Exploring the functionalities of React with TypeScript using the useState hook

I'm currently attempting to retrieve my project data from Firebase and store it in an array using hooks. Each project has a structure similar to: {name: "movie app", date: t, description: "this is my first app, a complete movie app"} //hooks const [p ...

The JavaScript function is facing an issue where it is not replacing the text accurately as anticipated when

I am currently working on a JS/JQ function that allows users to toggle between following and unfollowing a question. Depending on where the user clicks, they may encounter a link with text "Follow" or "Unfollow", or a button labeled "FOLLOW" or "UNFOLLOW ...

Ways to check if two strings share a common word using JavaScript

Seeking a clever solution to this problem, I am intrigued by who can come up with the most innovative approach. It seems that the key may lie in utilizing the split function along with a comparison loop. The dilemma at hand: My task involves merging vario ...

Ways to display scroll bar when hovering the mouse pointer?

When visiting the website YouTube, you may notice that their sidebar scrollbar becomes visible as soon as your mouse moves over it. I've been attempting to achieve this effect on my own div, but currently, the scrollbar only appears once I start scrol ...

What is the best way to transform this JSON data into an HTML table using JavaScript?

I am looking to dynamically create an HTML table based on changing json data. I want the table to maintain consistent alignment and width, similar to the example shown here. How can I convert the incoming json data into a well-structured HTML table? [ ...

Navigate the orbit control camera in a circular motion around the target object

Just starting out in the world of threejs. I've managed to create a cube with different colors on each face. This cube can be rotated using OrbitControl, and I have 6 buttons in Dat.GUI that control the camera position. My goal is to click "Animate t ...

Creating a text with a curved shape using React

While working on my react app, I wanted to incorporate circular/curved text. I came across a package called react-curved-text, but unfortunately, it didn't meet my expectations. The issue I faced was that although it curved the text, it didn't a ...