Issue with burger menu functionality, button unresponsive

Two files are involved in this issue, one is a Vue file and the other is a JavaScript file. The JavaScript file contains an array and the problem is being described in the console. Additionally, there may be an issue with items as sometimes the same error is encountered for them as well. Below is the code snippet: enter image description here

JavaScript file:

import Vue from "vue";

new Vue ({
    el: 'TopHead',
    show:false
});

Vue file named "TopHead":

<transition name="fade" mode="out-in">
    <i class="material-icons menu" v-if="!show" @click="switchShow" key="menu">menu</i>
    <i class="material-icons clear" v-else @click="switchShow" key="clear">clear</i>
  </transition>
  <transition name="fade">
    <ul v-if="show">
      <li v-for="item in items" :key="item"><a :href="item.url">{{ item.name }}</a></li>
    </ul>
  </transition>
<script>

export default {
data: function () {
return {
items: [
{name: 'Yarn', url: '#'},
{name: 'Needles', url: '#'},
{name: 'Hooks', url: '#'},
{name: 'Accessories', url: '#'},
{name: 'Gift Certificates', url: '#'},
{name: 'Patterns and Descriptions', url: '#'},
{name: 'Models', url: '#'},
], 
show: false
}
},
name: 'TopHead',
methods: {
switchShow() {
this.show = !this.show;
}
}
}
</script>

Answer №1

Errors can occur when working with props if you try to change them within the component that receives the prop, instead of passing the new value to the parent and changing it there. The issue is highlighted in this code snippet:

<i class="material-icons menu" v-if="!show" @click="show = !show" key="menu">menu</i>

The line @click="show = !show" mutates the value of show on click event. There are two solutions to this problem.

  1. Solution: Use show locally in your component
<script>
export default {
  data: function () {
    return {
      items: ['1','2','3'],
      show: false
    }
  },
  name: 'TopHead',
  methods: {
    switchShow() {
      this.show = this.show === false;
    }
  }
}
</script>

To modify show in your component, use the switchShow function. Simply utilize it on your icon like this:

<i class="material-icons clear" v-else @click="switchShow" key="clear"gt;clear</i>
  1. Solution: Emit the change to the parent
<script>
export default {
  data: function () {
    return {
      items: ['1','2','3']
    }
  },
  props: {
    show: Boolean
  },
  name: 'TopHead',
  methods: {
    emitShow() {
      this.$emit('emit-show');
    }
  }
}
</script>

<i class="material-icons clear" v-else @click="emitShow" key="clear"gt;clear</i>

This involves calling a function on the parent to handle the mutation of show. If the parent changes it within a function, similar to approach 1, then it will pass down the new value through props.

I suggest using approach 1 as it is easier to understand, and if no other component uses show, you can keep it within your component rather than in the parent.


Edit for newly encountered error

If you are using v-model:key with v-if, you must provide a unique identifier. The error lies here:

<li v-for="item in items" :key="item"gt;

... and ...

items: [
    {name: 'Yarn', url: '#'},
    {name: 'Needles', url: '#'},
    {name: 'Hooks', url: '#'},
    {name: 'Accessories', url: '#'},
    {name: 'Gift Certificates', url: '#'},
    {name: 'Patterns and descriptions', url: '#'},
    {name: 'Models', url: '#'},
  ], show: false
}

Each item in items is an object. When used as a key, they display as [object Object], regardless of their values. To fix this, simply use one of the object's values, like you did with the <a> tag:

<li v-for="item in items" :key="item.name"gt;

Answer №2

It is necessary for data to be a function that returns an object.

//...
data() {
  return {
    items: ['1'],
    show: false
  }
}

UPDATE: I just noticed that you are attempting to combine a .js file with a .vue file.

Vue is producing an error because TopHead.vue does not have "items" defined. You can either transfer the data() {} from the .js file to the .vue file, or change items and show to props.

Here's how I changed them to props:

<div id="TopHead">
  <top-head :items="myExternalItems"/>
</div>
// in your .js file
import TopHead from './TopHead.vue'
new Vue ({
    el: 'TopHead',
    components: {
       TopHead
    },
    data() {
      return {
        myExternalItems: ['1'],
      }
    }
});

In your .vue file:

export default {
  props: ['show', 'items']
}

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

Guide on transmitting data between NextJS and MongoDB

I'm facing an issue where the data from a form is being sent to MongoDB as undefined using nextJS and MongoDB. NewPlayerPage component: const newPlayerPage = (props) => { console.log('props: ' + props); const handleAddPlayer = a ...

Prevent animations on child elements with Vue.js

I am dealing with a scenario where I want to remove the fade transition on a child div within a <transition> component. The reason for nesting it is to prevent layout flickering, which can be demonstrated in a fiddle if necessary. In the fiddle belo ...

What could be the reason for the counter not being incremented when the button is clicked

While attempting to increase the counter in my test, I encountered an issue where pressing the button did not change the value. I tried using both fireEvent from React testing library and React test utils, but the value remained at 10. My project is using ...

This error message in AngularJS indicates that the argument 'fn' is not being recognized as a function

I am currently working with angularjs and typescript and I am attempting to create a directive in the following manner: Below is my controller : export const test1 = { template: require('./app.html'), controller($scope, $http) { ...

What is the best way to retrieve an element that has been altered in its state?

I encountered a scenario where I want an image to have a border when clicked, and if clicked again, the border should be removed. However, the border should also be removed if another image is clicked instead. I believe there are a couple of approaches to ...

Strange Reselect selector actions

It seems like my selector function is only triggered when one of the arguments changes, not both. Here's the selector I'm using to retrieve transactions from the state and apply two filters to them: export const getFilteredTransactionsSelector ...

Performing asynchronous ajax calls with jQuery

Here is some code I have that involves a list and making an ajax call for each element in the list: util.testMethod = function(list) { var map = new Map(); list.forEach(function(data) { $.ajax({ ...

Attempting to grasp the intricacies of HTML5/JS video playback quality

I've been diving deep into research on this topic, but I can't seem to find a straightforward answer to my specific query. My main focus is understanding the inner workings of how video players transition between different quality settings (480p, ...

The navigation bar options are not collapsing as intended

When I resize my page to width:750px;, my navigation bar is not collapsing the items. Despite trying to edit my CSS, I am still clueless. Here is my live page. This is the CSS for my slidebar: @media (max-width: 480px) { /* Slidebar width on extra small ...

Dockerfile unable to recognize environment variable

I'm currently working on a Vue application running with Docker, and I want to use environment variables to target specific project repos. However, when I try setting the env variables, they don't seem to be recognized in the Dockerfile. Can you ...

The functionality of react-waypoint's onEnter/onLeave event handlers seems to be malfunctioning

Recently, I experimented with react-waypoint to control the visibility of a div. The code works as intended by hiding the div when it reaches the waypoint inside onEnter. When the div is inside, the isInView state becomes true, which in turn triggers the d ...

Validate selected checkbox using JavaScript

Is there a way for me to achieve real-time updates when checking and unchecking multiple checkboxes in a list? Here's the code snippet I currently have: window.onload = function () { var input = document.getElementById('listTaxi'); fu ...

Who is the intended audience for the "engines" field in an npm package - consumers or developers?

As the creator of an npm library, I have included the current LTS versions of Node.js and npm in the package manifest under the engines field. This ensures that all contributors use the same versions I utilized for development: Node.js <a href="/cdn-cgi ...

Seeking assistance in configuring a dynamic payment amount feature on Stripe using Node.js

As a newcomer to node and javascript, I'm seeking guidance on how to proceed with the code below. I have copied it from the Stripe documentation, but I am unsure about the function for the commented token. Initially, everything was working fine with t ...

Even in report-only mode, Content Security Policy effectively blocks the execution of inline scripts

Currently, I have implemented a Content Security Policy (CSP) in 'Content-Security-Policy-Report-Only' mode with a specified report-uri. There is an inline JavaScript code running on the page that the CSP restricts. My initial expectation was tha ...

Angular connecting to the count of filtered items

Here's the array I'm working with: [ { type: "hhh", items: [ { "name": "EGFR", "type": "a", "selected": true } ] }, { type: "aaa", items: [ { ...

"Make sure to tick the checkbox if it's not already selected,

Could use some assistance with traversing and logic in this scenario. Here is the logic breakdown: If any checkbox in column3 is checked, then check the first column checkbox. If none in column 3 are selected, uncheck checkbox in column1. If column1 ...

Loading data table rows dynamically using Vuetify

I have a Vuetify datatable structured like this <v-data-table :items="items" :headers="headers" :search="search"> <template slot="items" slot-scope="props"> <td>{{props.item.id}}</td> <td& ...

Retrieving and storing successful response data in Angular JS using the $http service caching

My dataFactory is set up to retrieve posts in a simple manner: dataFactory.getPosts = function () { if (this.httpPostsData == null) { this.httpPostsData = $http.get("http://localhost/matImms/wp-json/posts?type=journey&filter[posts_per_page ...

Verify the password by checking each character as you type

Currently, I am trying to implement a real-time password matching feature. Is there anyone who can provide me with the code that verifies whether the entered passwords match character by character as they are being typed, and also checks the length upon ...