An issue occurred during rendering: `TypeError: Unable to retrieve the length property of an undefined value`

I want to display an overlay only when there is text in my search input.

Below is the template for my input field:

Input.vue:

<template>
    <div>
        <input v-model="query" class="input" placeholder="Global search..."></input>

    </div>
</template>
<script>
    export default {
        data() {
            return {
                query: '',
            };
        }
    };
</script>

When I check the console, I can see that query updates with the text entered into the input field.

Next, I try to pass this variable to another component which contains my overlay div:

Overlay.vue:

<template>
    <div v-if="this.$root.query.length > 0">
        <div class="search-overlay is-active"></div>
    </div>
</template>

But this approach results in an error message:

[Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined"

Can you spot what I am doing wrong here?

Answer №1

$app represents the highest-level element in the hierarchy (the component initialized using new Vue()), and it does not seem to be Input.vue.

Regardless, if Input.vue were actually the root component, the current method of accessing its state is considered inelegant. In order to facilitate data sharing among components, it is recommended to utilize props for one-way data flow from parent to child, or opt for a shared data store such as Vuex for more intricate scenarios.

Answer №2

It is not recommended to access component data in this way. Consider using VueX and state management patterns for a more effective solution.

If you choose not to use VueX or other tools for state management, you can utilize events like the example below:

var Input = Vue.component('custom-input', {
  name : "custom-input",
  template : "#custom-input-template",
  props : ["value"],
  methods : {
    onInput(){    
      this.$emit('input', this.$refs.queryInput.value)
    }
  },
  created() {
    console.log("Custom-input created")
  }
});

var Overlay = Vue.component('custom-overlay', {
  name : "custom-overlay",
  template : "#custom-overlay-template",
  props : ["query"],
  created() {
    console.log("Custom-overlay created")
  }
});

new Vue({
    el: "#app",
    components : {
      Input,
      Overlay
    },
    data: {
        query : null
    }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<div>
 <custom-input v-model="query"></custom-input>
 <custom-overlay v-show="query && query.length > 0" :query="query"></custom-overlay>
</div>
</div>


<script type="text/x-template" id="custom-input-template">
    <div>
        <input :value="value" ref="queryInput" class="input" placeholder="Global search..." @input="onInput"></input>
    </div>
</script>

<script type="text/x-template" id="custom-overlay-template">
  <div>
  {{query}}
  </div>
</script>

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

JavaScript that Implements MVC Architecture Using C#

When working on a cshtml page within my View, I am able to easily retrieve the URL to an action using this line of code: <h1>@Url.Action("NewComment", "Case")</h1> If I include the same code in JavaScript like this: <script> alert( ...

What is the best way to convert template interpolation using different words into a correct expression syntax in JavaScript regex?

I have a string that contains template interpolation along with words that are not inside the interpolation. The string can be in one of these various forms: foo{{bar}} {{foo}}bar foo{{bar}}baz {{foo}}{{bar}} foo {{foo}} {{foo}}bar{{baz}} The text interpo ...

Transferring information from offspring to parent

Greetings! I'm currently getting my feet wet with React and finding myself stuck on an issue regarding passing states. Is it possible for me to pass a child state to a parent component in order to selectively render other child components? ...

Is there a way to tally up the number of green items and display a <p> tag when every item has been marked green?

I have created a checklist that includes checkboxes. I am looking to display some text when all the checkboxes are checked and green. Can someone assist me with writing the code for this functionality? $(document).ready(function() { $("i").click(funct ...

Import Vue filters directly into the component specifically

I have a central filters file that contains multiple filters and I want to import only one specific filter into my component. Here is an example of what my filters file looks like: //filters.js import Vue from 'vue'; Vue.filter('shorten&ap ...

Implementing a dynamic tab change functionality with props in Material UI tabs

Observing the following example: Link to Material UI Tabs Suppose I have these tab components within a widget, and I wish to include an image or icon. How can I link the icon or image so that when clicked, it changes to a specific tab without using react- ...

Extracting data from XPath results reveals information beyond just the elements themselves

Having trouble using the getElementsByXPath function in CasperJS to return a specific string from an xpath I determined. Despite my efforts, it seems like the function is only returning data for the entire webpage instead of the desired string. var casper ...

if a condition is not being properly assessed

Currently, I am working on a $.ajax call to retrieve data in JSON format. Within this JSON data, there is an element called "status." My code snippet checks if the value of `data.status` is equal to "success" and performs some actions accordingly. Despite ...

Change the size of Jive Addon Tile in a vertical orientation

Seeking assistance with resizing the tile container in an angular application embedded within a Jive tile when the view changes. Any advice on how to tackle this issue? This particular tile is deployed to a Jive Cloud instance using a Jive add-on. ...

Terminate a browser tab with the click of an HTML button

I'm facing an issue with my HTML button - I need it to close the tab upon clicking. Unfortunately, the common methods seem to no longer work on newer versions of Chrome and Firefox. I've tried using these two solutions but they did not work: & ...

"Troubleshooting: Fixing the issue with jQuery datepicker not

After implementing the jQuery Datepicker on a field, I noticed that even though assigning a value to the field shows in Chrome's developer tools... https://i.sstatic.net/We7Ua.png Unfortunately, the assigned value does not show on the front end. I ...

Exploring Unicode Symbols for Icon Selection

I'm currently working on integrating an icon picker into my application that will enable the user to select a mathematical operator for data comparison. While I have successfully implemented the fontawesome-iconpicker on the page, I am encountering d ...

Creating a 24-hour bar chart using Flot Javascript, showcasing data points at each hour mark

I am attempting to create a 24-hour bar graph using Flot Charts, with a value corresponding to each hour. It seems that Flot utilizes epoch time for hour values. However, after running the code below, I encounter an issue where the chart does not display a ...

Guide on parsing JSON data received from the frontend

Here is the HTML code that I am working with: <div id="loginform"> <form class="loginIn" name="loginform"> <input type="text" name="login"> <input type="password" name="password"> <input type="submit" value="Войт ...

What should the AJAX file in TagManager jQuery look like?

I'm currently utilizing Tagsmanager with JQuery, which can be found at There is a feature that allows tags to be pushed via Ajax: jQuery(".tm-input").tagsManager({ AjaxPush: '/ajax/countries/push', AjaxPushAllTags: true, ...

Animating SVG elements with the rotation property in SVG.js

Currently, I am utilizing Javascript, Jquery, SVG, and SVG.js in my project. My goal is to rotate a circle around its origin while it's animating. The issue arises when the animation keeps restarting abruptly, causing a jittery motion. Here is the ini ...

Automatically updating the results section while executing SQL queries in PHP

Here is a JavaScript/Ajax code snippet: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready (function () { var updater = se ...

Adding Vuetify to your Astro project is a breeze!

Struggling with integrating Vuetify 3 into Astro using Vue integration. Here's my current setup: import { defineConfig } from 'astro/config'; import vue from '@astrojs/vue'; import vuetify from 'vite-plugin-vuetify'; / ...

Execute an xmlhttprequest and then redirect to a different URL

I'm a beginner when it comes to AJAX and JavaScript. My goal is to first show a confirmation box, then send an XMLHttpRequest if confirmed. After that, I want to redirect the user to a new page. Below is my current code: <script type="text/javascr ...

Guide on utilizing the disable feature in SortableJS for a Vue project

I have successfully implemented the draggable effect on my el table using element-ui-el-table-draggable and it's working perfectly. Now, I am looking to incorporate the disable option from SortableJS, but I'm unsure how to integrate these two fu ...