Unreachable variable in Vue 2.0

I am new to Vue and facing an issue with accessibility. I have two files.

The first file is App.vue where <router-view> is defined:

<script>

export default {
  name: 'app',
  data(){
    return{
      info: false,
    }
  },
  beforeMount(){
        example...
        this.info= true
        this.$router.push('/main'); //where in router-view visible is component Main.vue

      }
    }

</script>

The second file is the Main.vue component which is as follows:

<script>
export default{
    name: 'main',
    data(){
        return{

        }
    },
    beforeMount(){
        //what i want to do:
        console.log(App.data().info) //here should be visible true in console log
    } 
}

I want to access the property from the first file in the second file. How can I achieve this correctly? Thank you in advance.

Answer №1

Here are two approaches that come to mind:

  1. Passing Props to Route Components

For more information, check out this link

Incorporate the following code in your router setup:

import main from './main.vue'

    const router = new VueRouter({
      routes: [
        { path: '/main/:id', component: main }
      ]
    })

Inside your Main.vue file:

To access the variable: this.$route.params.id


  1. Store the data in a state manager and retrieve it using the state in another component with Vuex

Answer №2

In Vue.js, each component instance operates within its own isolated scope. This concept is further explained in the documentation here.

It is not recommended to directly access parent data from a child component's template. Instead, data should be passed down to child components using props.

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

Utilizing JavaScript within the Spring MVC form tag

Can you please assist me with the following question? I am currently working on a project using JSP, where we are utilizing Spring form tags. My issue involves creating two radio buttons that, when clicked, will display different options and pass the sele ...

React Native Redux Toolkit: Despite the state showing a non-serializable value, my object is confirmed to be serializable

I recently upgraded my traditional react-native with redux App to the modern redux-toolkit and encountered an error: A non-serializable value was found in the state, in the path: `currentUserSessionData.data`. Value:, CurrentUserSessionData { "isOnb ...

``What is the best way to create a v-toolbar with a multiline title in Vue.js

In my Vue.js app with Vuetify library, I am facing an issue with displaying v-cards titles of varying lengths. The problem is that the title breaks off and shows "...", instead of wrapping to multiple lines as needed. How can I change this? Template: < ...

The entire Sphere Geometry in three.js is not completely encompassed by the texture

Click here to view the image I'm trying to create a rotating moon. Everything works perfectly with MeshStandardMaterial (with color but no texture), however, when I apply a texture to the sphere geometry, it behaves strangely. The issue I'm facin ...

Unable to populate data in dropdown using Angular framework?

My datatable displays elements along with an edit button. At the top of the page, there is also an add button. The purpose of the add button is to add elements to the list, while the edit button allows for editing the data in a particular row. When the u ...

Can someone provide guidance on how to send serialized data using a jQuery.getScript() request?

Is it feasible to make a request for an external JS file while simultaneously sending serialized data in that same request? I want to provide some values to validate the request, but without including those values in the request URL. Upon receiving the po ...

Recursive array generation

Given an array 'featureList', the goal is to create a new array 'newArray' based on a specific ID. For example, for ID 5, the newArray would be ['MotherBoard','Antenna','Receiver'], where Receiver correspon ...

Extracting user input from an iframe and transferring it to another frame in HTML format

Can someone advise me on how to extract values from iframe1 and transmit them to iframe2 as HTML? I am open to either JavaScript or jQuery - no preference. As a beginner in javascript, I stumbled upon some code that seems relevant. <!DOCTYPE html> ...

Is there a way to preserve all the downloaded node modules in the package.json file?

Is there a way to keep track of all the node modules installed in package.json without the need for reinstalling them? I've heard about running npm init --yes, but I'm not entirely convinced if that will do the trick. Any assistance on this mat ...

What is the best way to handle multiple promises when loading a state in Angular?

When loading the /home state, I need to retrieve all users from the database in order to customize the home controller and view based on the logged-in user. Currently, in the :resolve section of the state configuration, I am fetching all 'posts' ...

How can eval() be effectively replaced in JavaScript?

Having trouble with javascript eval()? I've encountered bugs and decided to replace all instances of it. Here's an example of what I've changed: var abc = "item." + str3 + ".power"; abc = eval(abc); Now, it's been updated to: var abc ...

Collect all the attribute values of the checkboxes that have been checked and convert them

Is there a way to retrieve the attribute values of all checked checkboxes as an XML string? <input type="checkbox" id="chkDocId1" myattribute="myval1"/> <input type="checkbox" id="chkDocId2" myattribute="myval43"/> <input type="checkbox ...

Learn how to assign an ID to a React component in order to access it using the document.getElementById() method

After going through multiple inquiries, my understanding led me to believe that simply setting the id as shown below would suffice: <MyComponent id="myId"/> However, upon invoking document.getElementById() on the specified id, I receive a null resu ...

Utilizing the Sheet Elite API - Step-by-Step Guide for Sending Data to a Designated Sheet Through a POST Request

Recently, I've been working on a project that involves using the Sheet Best API to submit data directly to Google Sheets. However, I'm running into an issue where the data is only being sent to the first sheet out of three. Despite having all the ...

Is there a way to reset back to the default CSS styles?

I have a div container with a nested span element (simplified). <div class="divDash"> <span>XX</span> </div> The CSS styling for the div makes the span initially hidden and only visible when hovering over the parent div. .div ...

HTML - implementing a login system without the use of PHP

While I am aware that the answer may lean towards being negative, I am currently in the process of developing a series of web pages for an IST assignment in Year 9. Unfortunately, the web page cannot be hosted and our assessor lacks the expertise to utiliz ...

Using $store.commit with the @vue/composition-api in Nuxt: A comprehensive guide

<template> <div> <h1>Testing Vuex with Typescript</h1> <button @click="handleLogin">Click Me</button> </div> </template> <script lang="ts"> import { defineComponent } fr ...

The comprehensive guide to using ambient enum types in an exhaustive switch statement

Here is a function that maps a place to an emoji: function mapPlaceToEmoji(place: Place): string { switch (place) { case Place.FIRST: return ' ...

Choosing the next SELECT element with jQuery

JavaScript document.querySelectorAll('select[id^="_taskAssignedTo_"]').forEach(function(select) { if (select.value === "1") { select.nextElementSibling.querySelector('select[id^="_taskStatus_"]').disabled = false; } }); ...

Step-by-step guide on placing a geometry shape precisely at the mouse click location using ThreeJS

I'm attempting to create a circle in the exact position where the mouse is clicked, but the circle ends up being drawn slightly off. Can anyone pinpoint what needs to be adjusted in the code below? var camera = new THREE.PerspectiveCamera ...