Unlocking Component Variables Beyond the Bounds - Vuejs

Suppose I have a compound called <myCompound>, how can I access the ref or variables from the outside? For example:

myCompound.vue :

<script setup>
import { ref } from "vue";
const myString = ref("hi string");
</script>

<template>
  <div>
    <p>{{ myString }}</p>
  </div>
</template>

myPage.vue

<script setup>

import myCompound from "./compounds/myCompound.vue";
import { ref, onMounted } from "vue";

const myCompoundRef = ref();

onMounted(() => {
  console.log(myCompoundRef.value.myString)
})
</script>

<template>
  <div>
  <myCompound ref="myCompoundRef" />
  </div>
</template>

How can I achieve this with script setup:

myCompound.vue :

<template>
  <div>
    <p>{{ myString }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      myString: "hi string"
    }
  }
}
</script> 

myPage.vue

<template>
  <div>
  <myCompound ref="myCompoundRef" />
  </div>
</template>

<script>
import myCompound from "./compounds/myCompound.vue";
export default { 
  components: {
    myCompound
  },
  mounted() {
    console.log(this.$refs.myCompoundRef.myString)
  }
}
</script>

Are there certain ways to achieve this? I am using Nuxt 3, but I am open to other methods. I just want to understand how it all comes together...

Answer №1

To make it accessible, consider using the defineExpose macro like this:

<script setup>
import { ref } from "vue";
const myMessage = ref("hello message");

defineExpose({
  myMessage
})
</script>

<template>
  <div>
    <p>{{ myMessage }}</p>
  </div>
</template>

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

What is the best way to modify the URL path to eliminate a specific parameter?

Recently, I integrated authentication into my Vue.js application utilizing Amazon AWS Cognito. Although the authentication is functioning properly, I am looking to tidy up the URL and so far have not been successful in doing so. Following authentication w ...

Vue's reactivity fails to activate when utilizing Bootstrap 5's alert container

Why Vue's reactivity is not triggered when using Bootstrap 5's alert div? Take a look at my code: <template> <div> <div v-if="alertICDMsg!==''" id="alertICDCode" cl ...

Issue with onClick function causing failure to generate options in select menu

function getOption(){ var select = document.getElementById("dynamic-select"); if(select.options.length > 0) { var option = select.options[select.selectedIndex]; alert("Text: " + option.text + "\nValue: " + option.value); ...

Methods for delivering static resources on multiple routes in Express JS

Is there a way to effectively serve static resources for all routes in Express JS? I attempted to serve files with static resources using the following code snippet: app.use(Express.static(`${this.PATH}`)); app.use(Cors()); app.use(Express.json()); app.g ...

SystemJS could not locate the root directory for RxJS

There seems to be an issue with SystemJS loading rxjs modules on Windows, as it throws a 404 Not Found error on the rxjs directory. This problem does not occur on OSX, and all modules are up to date. GET http://localhost:8080/node_modules/rxjs/ 404 (Not F ...

What steps should I take to ensure that Vim properly formats the indentation for this JavaScript code?

Currently an Emacs user, but trying out Vim for a change. :) I'm really enjoying the quick keystrokes and the overall philosophy of Vim, however I've been running into some issues with the more advanced features. One problem I'm having is w ...

Switch between multiple unordered lists (ul) so that when one list is clicked, the other lists reset to their initial state as though they were never

When I click on the first item in the ul list, it should slideToggle() to show its corresponding items. Similarly, when I click on the second item in the ul list, its items should slideToggle(), but the first ul list remains visible as well. What I am tryi ...

Troubleshooting problem with candlesticks in Vue using google charts

I need assistance with creating a candlestick chart in vue.js utilizing vue-google-charts. I have successfully implemented other types of charts such as line, column, and pie; however, the candlestick chart is not displaying correctly. Can you help me id ...

Dynamic field validation using jQuery

I am currently developing a wizard feature that retrieves employees dynamically from the backend. The employee table is created with a radio input field and then inserted into my HTML code: $.ajax({ method: "get", url: '/fetchEmployees/' ...

Nodejs - Utilizing Express and Mongoose to Implement URL Routing by Name

My Express 4 server has CRUD routes specifically for authors: router.get('/authors', AuthorsController.index); router.post('/authors', AuthorsController.store); router.get('/authors/:name', AuthorsController.show) ...

What is the best way to retrieve data from within a for loop in javascript?

Seeking assistance in Typescript (javascript) to ensure that the code inside the for loop completes execution before returning I have a text box where users input strings, and I'm searching for numbers following '#'. I've created a fun ...

Changing a numeric string into a number within an Angular 2 application

Looking for advice on comparing Angular 2 expressions. I have an array of data stored as numeric strings in my database and I need to convert them to numbers before applying a condition with ngClass for styling purposes. Any suggestions on how to perform ...

Exploring the Power of jQuery's Vote-Object and Scope

This is a coding dilemma related to JavaScript. The reference to this particular website is not necessary and therefore does not pertain to meta. In my current project, I am developing a Greasemonkey script that automatically loads more answers onto the i ...

What is the best way to organize divs in a grid layout that adapts to different screen sizes, similar to the style

Is there a way to align multiple elements of varying heights against the top of a container, similar to what is seen on Wolfram's homepage? I noticed that they used a lot of JavaScript and absolute positioning in their code, but I'm wondering if ...

choose and adjust elements within a three-dimensional scene using three.js

I have a JSON file containing object data that I load into my scene using ObjectLoader. After adding the objects to the scene, I want to customize their textures by adding parameters like THREE.SmoothShading and an envMap. I know how to find a specific obj ...

Can anyone explain why I keep encountering an endless loop when using react hooks?

Having a bit of trouble with fetching data from a JS file that is mimicking an API with some endpoint methods. When I console log the data, everything seems fine, but for some reason, I keep running into an infinite loop when using hooks. I've tried t ...

Validator acting as a computed setter

I am facing a challenge with using a computed property to track the value in ElementUI's el-input component. The issue is that the desired value is not being displayed within the component. Specifically, I aim to limit the input length to three charac ...

Incorporating User Input: Adding Paragraph Elements with HTML and Javascript to a Div Container

I am attempting to test my ability by creating a basic webpage. My goal is to take the text entered by the user in a textarea and add it to the page using a button. This button should generate a new paragraph element, place the user input inside of it, and ...

The scrolling on the image listing webpage is not as fluid as desired

I'm currently working on building a website for displaying images in Angular, similar to Google Photos. The site includes a custom scrollbar that displays the month and year. I want the image list to scroll when the user moves the scrollbar thumb. Her ...

Tips for switching images in a grid using jQuery

I have implemented an image grid using flexbox on a website I am developing. The grid consists of 8 boxes, and my goal is to randomly select one box every 2 seconds and assign it one of 12 random images. My strategy involves creating an array containing UR ...