Skip to content
Advertisement

TypeError: Cannot set properties of undefined (setting ‘message’) in Vue

i’m new in Vue.js, so there are concepts that maybe i’m missing. The thing is that i’ve been trying to do this for months, but i couldn’t get a solution. What i’m trying to do is change the message of a v-alert but on another js script, importing the variable of said message and changing it.

This is a piece of my App.vue

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

I have this declared variables on appController.js

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

      }

What i’m trying to do is getting that variables on another js script, so i can modify it like this thing i did on loginController.js

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

But when i call loginFunc from a v-btn, i get these errors on 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 i am doing wrong? What can i do to solve that and change content of var message, so i can show it on the v-alert?

Advertisement

Answer

alert in undefined because appController.js doesn’t export alert. Based on the code you shared, it exports a data method which has the alert.

So to access it, it would look something like…

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

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

This would make it accessible, but not sure if that’s what you want.

If you want to be able to edit a value from anywhere you would use a a global store. To make it reactive you could use ref or reactive but only with composition API but also using a global store like vuex, pinia or oeve vue observable. If you have a single alert that watches for that globally-accessible and reactive value, it would then update.

Note that even in your current example, the value appears not to be globally accessible nor reactive, so you would have to manage reactivity and pass it to the component.

If you’re using vue3, you can have a look at this sample via vue SFC playground. Note that it’s using reactive to manage a “singleton” global state and the alert component is always present, but the visibility is handled internally.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement