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 https://i.sstatic.net/AYKAK.png

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

What is the best way to extract a list of particular items from a nested array?

When I execute the following code: var url="https://en.wikipedia.org/w/api.php?format=json&action=query&prop=categories&titles=Victory_Tests&callback=?"; $.getJSON(url,function(data){ $.each(data, function(i, item) { console.lo ...

Tips for integrating JavaScript code into React JS applications

I am attempting to create a scrollable table that scrolls both horizontally and vertically, using the example provided by . In my project directory under src/components/ScrollExample.js, I have copied and pasted the HTML code. In addition, in src/styles/c ...

Using the factory pattern in a Node.js (Express) application

As I delved into the realm of design patterns, I found myself drawn to the factory pattern. However, as I perused through code written by others, I noticed that this particular pattern wasn't as prevalent, especially in newer stacks. Take for example ...

Calling gtag("event") from an API route in NextJS

Is there a way to log an event on Google Analytics when an API route is accessed? Currently, my gtag implementation looks like this: export const logEvent = ({ action, category, label, value }: LogEventProps) => { (window as any).gtag("event&quo ...

Tapping into the space outside the MUI Modal Component in a React application

Can Modal Component in MUI be used with a chat bot? When the modal is open, can users interact with buttons and inputs outside of it? How can this be implemented? I want to be able to click outside the modal without closing it. Modal open={open} onClo ...

Can a single volume control be used to manage the audio of multiple sources at once?

I am currently working on a project for my personal interactive video website. I am trying to figure out how to create one volume control that can adjust the audio for multiple tracks at once. Can anyone help me with this? So far, I have successfully crea ...

How to toggle hidden links with AngularJS or vanilla JavaScript with a click事件

When the "Show all" button is clicked, I would like to display all elements. If the "1st half" link is clicked, I want to show "abc", "def", and "ghi". When the 2nd link "2nd half" is clicked, I want to display "jkl", "mno", and "pqr". Then, when the "show ...

Performance problem with 'Point-along-path' d3 visualization

I recently explored a d3 visualization where a point moves along a path, following the code example provided at https://bl.ocks.org/mbostock/1705868. During this movement, I observed that the CPU usage ranges from 7 to 11%. In my current project, there ar ...

What is the best approach for addressing null values within my sorting function?

I created a React table with sortable headers for ascending and descending values. It works by converting string values to numbers for sorting. However, my numeric(x) function encounters an issue when it comes across a null value in my dataset. This is th ...

Template does not recognize the content of computed property, however it is successfully logged in the lifecycle hook

I'm currently building a webshop that allows users to order products individually without affecting the contents of their cart. I've set it up so that there is a shared page for both viewing your cart items and selecting a single product. This in ...

Can an in-progress NPM package be tested using NPX?

I am currently developing an NPM package that is designed to be used exclusively through npx *, similar to packages like create-nuxt-app. Is there a method to test my package using npx *? Essentially, I want to run my bin script without actually installin ...

When the return false statement is included, the form fails to submit and instead refreshes on the current page

I recently discussed an issue regarding triggering a dialog box before confirming a submit action. Unfortunately, after implementing this, the document no longer submits when expected. Instead, it just remains on the same page with the same settings. I h ...

Wait for AngularJS to load when the background image of a div becomes visible

Currently, I am utilizing the ng-repeat feature to fetch data from a $http.post request and then save it to the $scope.data variable. <div ng-repeat="key in [] | range:data.pages"> <div class="pageBackground" id="page_{{ (key+1) }}" ng-style= ...

The troubleshooting of a find method in Mongoose

Why is it necessary to use await twice when calling the model function, even though we already used await in the model itself: async function model() { return await data.find({}, '-_id -__v') } When I console.log await data.find({}, '-_id ...

JS is programmed to automatically redirect the user after they have clicked on a div element and a

I'm having trouble with this code that is supposed to redirect a user after they click on the div and then the next button. It's not working for me :( Here is the code I am using: $("a.xxx").click(function() { $(this).toggleClass("yyy"). ...

Discord.js: Merging strings while pushing to an array

I am currently updating an embed message to notify users who have "enlisted" in a list by reacting. However, I am encountering an issue where the strings from the entire array are getting combined when the length of the array reaches 2 before adding a new ...

Twilio's phone calls are programmed to end after just 2 minutes

For the past week, I've been dealing with a frustrating issue where calls are being automatically disconnected after 2 minutes of recording. Here is the TwiML code: <Response> <Say voice="woman" language="en">Hii Welcome to our App</Sa ...

Automatically update div content using AJAX in a different approach

In my situation, I am facing a unique challenge compared to other queries. I have a div element with the following code <div id="ondiv"><?php ?></div> Within this PHP section are details of people who are currently online. Ideally, when ...

Troubleshooting Material-UI: The Mystery of the Missing Dialog

I have been struggling with getting a pop-up dialog to appear when a form is incorrectly filled out. Despite my efforts, the code that should trigger the dialog upon submission does not seem to be working as expected. The function renderError(), responsib ...

Dealing with incorrect routes found in both documents

In my current project, I am facing an issue where I need to handle invalid routes and display a message in Node.js. I have two separate files, one for users and one for tasks. If a user accesses a route that does not exist, I want to show an error message ...