Troubleshooting: Vue Component Unable to Locate Property

Just dipping my toes into Vue with a simple test implementation and running into some trouble breaking down data into components. Let's take a closer look at the code:

<body>
    <header id="main-header">
       <custom-header></custom-header>
    </header>
</body>

Here's where I create a new Vue instance tied to #main-header:

import CustomHeader from '../header.vue';

const chx = {
    dates: { dateFormatted:"2016-01-01"},
    title: "Hello World",
    settingsVisible: false
} 

const header = new Vue({
    el: '#main-header',
    data: chx,
    components: {
        'custom-header': CustomHeader
    },
    methods: {
        run: function() {
            console.log('run');
        },
        print: function() {
            window.print()
        },
        save: function() {
            console.log('save');
        }
    }
});

Let's also take a peek at the template being imported:

<template>
<div>
    <div class="header-menu">
        <img class="logo" src="images/logo.png">
    </div>
    <i v-on:click="run" id="run" class="fa fa-3x fa-play-circle run-icon no-print" aria-hidden="true"></i>
    <div class="header-menu">
        <h1 id="date-range-label"><span v-show="dates.startFormatted">{{dates.startFormatted}} - {{dates.endFormatted}}</span></h1>
        <i v-on:click="settingsVisible = !settingsVisible" id="settings" class="fa fa-2x fa-cog settings-icon no-print"></i>
    </div>
</div>
</template>

<script>
    export default {
        props: ['title', 'dates']
    }
</script>

The main issue here is that my template is unable to access any of the data within the chx object I've defined, resulting in an error message

"TypeError: Cannot read property 'startFormatted' of undefined"
. It seems like I might need to utilize bind, but I'm unsure how to properly integrate it with v-show and v-on.

Answer №1

To begin, you must establish a prop in the header.vue component like this:

props: {
    'propname': { type: Object }
}

Next, pass the chx object created in the parent component:

<custom-header :propname="chx"></custom-header>

This will allow you to access the parent's data in the child component:

{{ propname.dates.startFormatted }}

For the second part of the query, trigger an event to inform the parent component about updating the settingsVisible. Here is one way to approach it:

<i v-on:click="toggleSettings()" id="settings" class="..."></i>
//
//
methods: {
    toggleSettings() { this.$emit('toggle'); }
}

In the parent component, listen for the toggle event:

<custom-header :propname="chx" v-on:toggle="chx.settingsVisible = !chxsettingsVisible"></custom-header>

For further details, refer to this guide.

Happy coding!

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 .forEach() method in Javascript is not suitable for DOM nodes as they are subject to change during the iteration

Having an issue with moving all DOM elements from one node to another, I initially used this code: div.childNodes.forEach((n) => me.container.appendChild(n)); However, I noticed that only half of the nodes were being copied. It seems that the problem ...

Consider yourself a module for npm, just like a node

I'm currently working on a Javascript project that has been released as a node module. In some parts of the source code, I have used relative paths to import other files within the project: // <this_module_path>/action/foo.js import execution f ...

The back button on an Angular JS application should display a confirmation dialog when pressed

I am currently working on an AngularJS mobile app that consists of various modules. One of my requirements is to access the device's back button within the application, and I also need a dialog with "OK" and "Cancel" options. Clicking on "OK" should ...

VueJS is preventing the closure of the modal through jQuery

Within the index.blade.php page, I have the following code snippet: <div id="books_listing" class="container"> <div class="alert alert-success" role="alert"> <p>Book suggestions has been enabled.</p> <span cl ...

I want to retrieve a complete HTML page using an AJAX request

I am trying to retrieve the content of a specific page, but encountering issues when using this function: function getResult() { var url="http://service.semanticproxy.com/processurl/ftfu27m3k66dvc3r43bzfneh/html/http://www.smallbiztechnology.c ...

I am experiencing an issue with Array.some not functioning properly within my React component, whereas Array.map is working

I am attempting to utilize Array.prototype.some() within my React component to check if a particular value exists in my array of objects. However, I keep encountering the error message data.some(...) is not a function. Interestingly, Array.prototype.map() ...

Iteratively modify each essential attribute of a JSON object

In my data set, I have moisture levels recorded at various timestamps in a JSON object: { "values": { "21-Aug-2020 20:28:06:611591": "58.59", "21-Aug-2020 20:28:09:615714": "71.42", "21-A ...

An issue arose during the installation of nodemon and jest, about errors with versions and a pes

Currently, I am facing an issue while trying to set up jest and nodemon for my nodejs project. My development environment includes vscode, npm version 6.13.7, and node version 13.8.0. Whenever I try to install nodemon via the command line, the console disp ...

Update the URL path with the selected tab item displayed

Is there a way to show the selected tab item in the URL path? I came across this example using Material UI: import * as React from 'react'; import Tabs from '@mui/material/Tabs'; import Tab from '@mui/material/Tab'; import Typ ...

Quantifying the passage of time for data entry

Looking to create a quiz form where I can track how long it takes users to input/select answers. I attempted the following code but the timing seems off: $('input, select').on('focus', function(event) { el = $(this); name ...

Tips on preventing right-click actions in jqGrid

While utilizing onSelectRow in a jqGrid, I have noticed that it functions properly when clicking with the left mouse button. However, when right-clicking, it still triggers the function. My aim is for the right-click to perform its usual action (such as di ...

Add additional tags to a Vue component that has already been created

Is it possible to dynamically add markup to existing components without directly editing them? Consider this scenario: <!-- Example of an arbitrary component X --> <template> <div> <!-- I would like to insert a headline here -- ...

Combining mouse interactions with animated bar transitions

I want to create a graph with dynamic bar height transitions whenever it is drawn or redrawn. Once the bars are displayed, I would like mouse events (mouseenter, mouseleave, and mousemove) to trigger a tooltip showing information about the specific bar bei ...

Tips on enclosing <li> elements within <ul> tags

Whenever I trigger the button within the .items class, it generates <li> elements in the following manner: <ul class="items"> <ul class="items"> <li>img1</li> ...

Exploring Next.js' dynamic routes with an alternative URL approach

Currently in the process of transitioning a React project to Next.js, I've encountered a minor issue with Dynamic Routing that doesn't seem to have any readily available solutions online. I have multiple information pages that utilize the same c ...

Learn how to obtain a response for a specific query using the `useQueries` function

Can we identify the response obtained from using useQueries? For instance, const ids = ['dg1', 'pt3', 'bn5']; const data = useQueries( ids.map(id => ( { queryKey: ['friends', id], queryFn: () =&g ...

Utilizing modal functionality for seamless integration of new data into mui-datatable

When trying to add a new data entry using a modal box, I encountered an issue where the new data was not being added to the datatable. Is there a solution for this problem? Below is the code snippet I used: let id = 0; function createData(name, provider) ...

jQuery DataTables covering a CSS-anchored menu bar

My webpage has a pinned navigation menu bar at the top and some tables with interactive features using jQuery's DataTables. However, after implementing jQuery, I encountered an issue where the tables cover the menu when scrolling down, making it uncli ...

Transform them into async/await in JavaScript

Exploring the promise-retry library, I discovered the following syntax: promiseRetry(function (retry, number) { return doSomething() .catch(retry); }) .then(function (value) { // .. }, function (err) { // .. }); Since I am utilizing a ...

Attempting to download an image through an axios fetch call

There is an issue I am facing while trying to retrieve an image from the website www.thispersondoesnotexit.com. function getImage() { axios({ method: 'get', url: 'https://www.thispersondoesnotexist.com/image' }) ...