Guide on transferring data from a component to App.vue in Vue 3, even with a router-view in the mix

I have the following layout:

  • src
    • components
      • Footer.vue
    • views
      • Page.vue
    • App.vue

I want to access the 'message' variable in App.vue, but I'm unsure how to do it since Footer.vue is not a direct child of App.vue (but rather a child of Page.Vue which - through the router - is a child of App.vue).

What changes should I make to my files? They currently look like this - and no message is displayed in App.vue:

//App.vue
<template>
  <p>The message is: {{ message }}</p>
  <router-view />
</template>

<style lang="scss">
@import "./_scss/main.scss";
</style>

.

//Page.vue
<template>
  <Footer/>
</template>

<script>
import Footer from '@/components/Footer.vue'

export default {
  components: {
    Footer
  }
}
</script>

.

//Footer.vue
<template>
  <input v-model="message" placeholder="Edit me">
  <p>The message is: {{ message }}</p>
</template>

<script>
export default {
    data() {
        return {
            message: ''
        }
    }
}
</script>

Answer №1

How about exploring the Composition API along with using ES6 modules?

@/compositions/composition.js
import { ref } from 'vue'

const message = ref('test');

export const useComposition = function() {

  // other functions, for example to mutate message ref
  
  return {
    message,
    // ...
  }
}

You can then easily import your composition in components that require access to the message:

// Footer.vue, App.vue
<script>
import { defineComponent } from 'vue'
import { useComposition } from '@/compositions/composition'

export default defineComponent({
  setup() {
    const { message } = useComposition();

    return { // make it available in <template>
      message
    }
  },
})
</script>

If you're looking to jumpstart your journey with the Composition API, check out this resource.

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 swap out an element in vue.js?

Here is the code I am working with: window.onload = (event) => { new Vue({ el: "#test", mounted: function() { this.fetch(); setInterval(this.fetch, 60000); ...

Retrieving data from Firestore yields an empty result

Having trouble reading from Firestore within a function, even though writes are working fine. Despite following examples on the given link, the query below and its variations result in an empty promise: module.exports.customerByPhone = phone => { r ...

What is the best way to sort through an array using JavaScript?

Here's an array for you: values = ["10%", 1000, "5%", 2000] I'm looking to split this into two separate arrays like so: percentages = ["10%","5%"] numbers = [1000,2000] How can I achieve this using JavaSc ...

When trying to import the "firebase/app" module, an error occurred stating that the default condition should be the last one to be considered

Greetings! I am diving into the world of webpack and firebase. Every time I use: import { initializeApp } from "firebase/app"; I encounter this error message: Here is my file structure: index.html: <!DOCTYPE html> <html lang="en& ...

How to retrieve the database's unique identifier instead of the default ID in VUE?

Hey there, I have a method called getAllEvents() that looks like this: getAllEvents() { var requestOptions = { method: "GET", redirect: "follow", }; let snapshot= fetch("http://localhost:8080/eve ...

Retrieving a boolean value from a function that includes an asynchronous AJAX request

In my calendar application, I am working with an array of dates: <div v-for="date in dates">{{ date }}</div> I want to apply a conditional class based on the outcome of an isWeekend() method that involves making an API call: <div v-for="d ...

`In Node.js, retry attempts resulted in an HTTP 504 status code.`

I have a scenario where my http server always returns a 504 status code: const express = require('express') const app = express() app.get('/', (req, res) => { console.log('I AM HERE'); res.status(504).send('N ...

Switch up the key while iterating through a JSON object

Can you modify the key while iterating through objects using an external variable? Picture it like this: var data = [{ "id": 1, "name": "Simon", "age": 13 }, { "id": 2, "name": "Helga", "age": 18 }, { "id": 3, "name": "Tom ...

What are some techniques for breaking down or streamlining typescript code structures?

Within my TypeScript class, I have a skip function. In the interface, I've specified that the data is coming from the backend. Now, on the frontend, I want to be able to rename the backend variables as demonstrated below. There are multiple variables ...

Extracting specific attributes from one array in Vue.js to populate another array

I've been trying to transfer some attributes from the Zamestnanci array to the archivovany array, but nothing seems to be working. Every time I attempt, I either get an HTTP error 415 or 400 because the attributes in archivovany are null. <script&g ...

Exploring the power of jQuery's deferred method and utilizing the ajax beforeSend

Using the deferred object in $.ajax allows for: Replacing the success-callback with the deferred-method done() Replacing the error-callback with the deferred-method fail() And replacing the complete-callback with always() When using: var jqxhr = $.ajax ...

Three.js - Rotation does not follow local orientation accurately

In my current project, I have created an extensive array of objects centered around a focal point within a scene. My goal is to manipulate these objects along their local axes. Initially, I aligned all the objects to face the origin by using a reference ob ...

Setting a default value in Vue props if it doesn't pass validation: A guide

Is it possible to assign a default value to a prop using a validator? For instance, if the current prop does not pass the validator and is less than 3, I would like to automatically set the value to 1. Here's an example: currentStep: { type ...

I attempted to create a test scenario to verify that the length of the tasks array is not negative. However, when trying to test this using 'not.toBe' in the code below, an error was encountered

app.js var todos=[]; todos=['to-do one', 'to-do two']; module.exports=todos; app.test.js const todos=require('./app') test('should have a length of at least 0',()=>{ expect(todos.length).toBeGreaterThanOrEqu ...

Tips on removing authentication token when logging out in react native

Working with the Django Rest Framework and React Native for the front-end, I am currently facing an issue where the authentication token persists even after a user logs out from the front-end. This is evident as the token still shows in the Django admin pa ...

Tips for clearing out text in a <p> tag with javascript when it exceeds a specific length of 100 characters

Is there a way to automatically truncate text to (...) when it exceeds 100 characters inside a paragraph with the class .class? For instance, if I have a long paragraph like this: <div class='classname'> <p>Lorem ipsum dolor sit ame ...

Guide to dynamically add tr element using CSS to a table

While using the $.each function in jQuery, I am retrieving data and adding it to a table in the following manner: $.each(segment, function (index, innerSegment) { var tr; tr = $('<tr/>'); tr.append("<td>" + segment[i].Airline.Air ...

Unlock real-time alerts with the power of JavaScript and PHP!

I am currently working on enhancing my skills in javascript. I have a basic idea of what I want to achieve. My goal is to create an automated javascript function that accesses a php page. This php page will create an array of new notifications for the ja ...

Top Method for Reloading Element-Specific JavaScript When Replacing Elements

Is there a better way to re-initialize JavaScript without needing a page refresh? I'm currently struggling with appending an MDBootstrap <select> tag, which involves more than just adding a child element. Instead, I have to remove the element an ...

Exploring Vue's reactivity using the composition API and cloning props

In my current component setup, I am receiving props from a parent. However, I am facing an issue where I only want to clone these props without any changes affecting the parent component. <template> <input-text v-model="form.name" /&g ...