Error in Vue: Trying to set a property ('message') on an undefined object

As a newcomer to Vue.js, there are some concepts that I may be overlooking. Despite working on it for months, I have been unable to find a solution. My goal is to change the message displayed in a v-alert by using a separate JavaScript script to import the message variable and alter it.

Below is a snippet from my App.vue file:

<v-app>
  <v-alert transition="scale-transition" :type="success" max-width="280" height="55" class="justify-center">{{alert.message}}</v-alert>
...

In my appController.js file, I have declared the following variables:

export default{
  data () {
    return {
      alert:{
        visible: true,
        type: "success",
        message: "test"

      }

My objective is to access these variables in another JavaScript script and modify them. Here is an example from my loginController.js file:

import {alert} from './appController.js';
export default {
 methods: {
    loginFunc() {
      //When loginFunc is called, the message content changes to "Test 2"
      alert.message = "Test 2";
    }
 }
}

However, when I trigger loginFunc from a v-btn, I encounter the following errors in the console:

vue.runtime.esm.js?c320:619 [Vue warn]: Error in v-on handler: "TypeError: Cannot set properties of undefined (setting 'message')"

TypeError: Cannot set properties of undefined (setting 'message')

What am I doing incorrectly? How can I resolve this issue and change the content of the message variable to be displayed in the v-alert?

Answer №1

alert is not defined because appController.js does not export alert. From the code provided, it seems to export a data method that contains the alert.

To access it, you would need code similar to this...

import {data} from './appController.js';
const { alert } = data();

export default {
  methods: {
    loginFunc() {
      alert.message = "Test 2";
    }
  }
}

This setup should make it accessible, but it may not align with your requirements.

If you need to edit a value globally and create reactivity, consider using a global store. To ensure reactivity, you can utilize ref or reactive, specifically with the composition API and frameworks like vuex, pinia, or Vue observable. By having a single alert watching for this globally-accessible reactive value, it will update accordingly.

If the current example lacks global accessibility and reactivity, you will have to manage reactivity yourself and pass it down to the components.

If you're working with vue3, check out this sample on the vue SFC playground. It showcases the use of reactive to handle a "singleton" global state, with the alert component always present while internal visibility management handles its display.

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

Express server encounters a 404 error while processing a POST request

Recently, I encountered an issue while trying to post data to my express server using a function that is triggered by clicking a button. Here's the code snippet of the function: const fetchData = async () => { const response = await fetch(&apos ...

Using GraphicsMagick in combination with Node.js to upload a fresh image file to AWS S3: A step-by-step guide

I've encountered an issue while trying to upload images to S3 - phone images appear rotated due to EXIF data. To address this problem, I came across a tool called graphicsmagick which claims to remove EXIF data and resize images to 500px wide. However ...

What is the best way to set a value to null in JavaScript?

Seeking assistance with the "Days Of The Week Exercise" in JavaScript. I have searched MDN and made numerous attempts, but I am still unsure about what null represents and how to effectively use it. If the argument (num) is less than 1 or greater than 7, ...

The second JSP page fails to load following an AJAX POST request

The following code snippet is found in page1.jsp. $.ajax({ type: "post", url: "page2.jsp", data: newdata, success:function(msg){ return msg; } ...

Is there a method to introduce a line break for each piece of data that is shown?

I am currently working with an array and have successfully displayed it on the screen. My inquiry is whether it is feasible to insert a line break for each of the data points it presents. { name: "cartItems", label: "Product Name ...

Switching effortlessly between Fixed and Relative positioning

As I work on creating a unique scrolling experience, I aim to have elements stop at specific points and animate before returning to normal scroll behavior once the user reaches the final point of the page. Essentially, when div X reaches the middle of the ...

Rearrange the li elements within multiple ul lists using JavaScript

Is there a way to reorder multiple ul-lists on my website using JavaScript? An example of the lists may be as follows: $(document).ready(function() { var ul = $('ul.filelist'); for (let u = 0; u < ul.length; u++) { const element = ul[ ...

Build React Native for Android Instant Apps

After working as a Native Android Developer, I have recently joined a team that is developing an app using React-Native. My current task involves refactoring a previous app that I built using React-Native. The app I previously worked on supported Instant ...

Using JQuery, retrieve all field values on click, excluding the value of the closest field in each row

I have a dynamic table where each row consists of an input field and a button. I am searching for a simpler way to select all input fields except the one in the current row when clicking the button in each row. All input fields have the same name and the r ...

Tally up every digit until they match the data attribute

I have a challenge with counting a few bars until they reach a specific value set in their data-line attribute. Below is the code I am currently using where I have tried to use setInterval to increment the counter, but I am unable to clear the interval whe ...

The art of perfect alignment: Mastering the positioning of Material-UI Grid

This issue has been resolved Hey there, I'm currently working on a React App with Material-UI and I'm trying to center a Grid item that includes a Card along with two additional Grid items. Below is the relevant code snippet. Although the Cards ...

Guide to setting up an object array in JavaScript with unique child elements and no duplicate values

I have an array that looks like this: sampleArray = ["x", "y", "z". "a.b", "a.b.c", "a.b.d", "a.e.f", "a.e.g"] However, I am aiming to transform it into the following structure, or something similar to it: newArray: [ { "x": [] }, ...

Passing data from PHP to jQuery in a file upload script

I'm facing a problem that I can't seem to solve on my own. What I am trying to achieve is to upload a file to the server via PHP (upload.php), generate a new filename, and then pass that new filename to my webpage (upload.html). Within my uploa ...

Is there a way to manually trigger a re-render of all React components on a page generated using array.map?

Within my parent component (Game), I am rendering child components (Card) from an array. Additionally, there is a Menu component that triggers a callback to Game in order to change its state. When switching levels (via a button click on the Menu), I want a ...

Step-by-step guide on removing the focusin event listener from a Bootstrap 5 modal

My current app has a legacy modal that uses a kendo dropdown list element bound to an ajax call with filtering. I'm trying to avoid rewriting this component if possible. However, there is an issue where when the modal opens and you focus on the dropdo ...

Exploring the possibilities of using React for looping?

I have integrated Dexie.js with React for this specific example. However, the implementation details are not of great importance to me. My main focus is on finding out how to iterate through all objects in my IndexDB database using React. In the code snip ...

Angular ngFor Directive Failing to Display Menu Item Information on Right-Click Context Menu

Currently encountering an issue with implementing a right-click function in my context menu. The menu items are not appearing due to the second ngFor="let row" condition... however, I require the selected row object from a right click to pass in a JSON val ...

What could be causing the beforeRouteUpdate function to not successfully update the route

I have implemented the products page using vueJS and an API. The page displays categories on the left side and products on the right side. The goal is to show products when a category is clicked, but the component is not loading as expected. I need help ...

Integrating TypeScript into an established create-react-app project

Struggling to integrate TypeScript into an existing create-react-app? I've always added it at the beginning of a project using create-react-app my-app --scripts-version=react-scripts-ts, but that's not working this time. The only "solution" I co ...

What is the best method for eliminating buttons and text in a row using CSS?

I faced an issue when trying to create a row, so I improvised with the following setup. However, I actually need a proper row layout for both the Google button and telephone number button. Here are my CSS snippets: .google-button { color: white; borde ...