Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'How to acccess data property inside setup in vue 3?

I am trying to access data property inside setup() in vue 3 but is giving me this error

TypeError: Cannot read property '$localStorage' of undefined

data()

  data() {
    return {
      $localStorage: {},

}

setup

  setup() {
   this.$localStorage
}

How i can access this property inside setup()?

like image 671
web pakistan Avatar asked Jan 29 '26 11:01

web pakistan


1 Answers

One solution would be importing getCurrentInstance from vue and use it in onMounted lifecycle or in a consumable:

import { onMounted, getCurrentInstance } from "vue";

export default {
  data() {
    return {
      key: "test",
    };
  },
  setup() {
    onMounted(() => {
      console.log(getCurrentInstance().data.key);
    });
  },
};

However, this usage is highly discouraged as stated in here.

Instead you could define that data property in setup using ref or reactive like this:

import { ref } from "vue";

export default {
  setup() {
    const $localStorage = ref({});
  },
};

or

import { reactive } from "vue";

export default {
  setup() {
    const $localStorage = reactive({});
  },
};

These solutions will work if your data and setup function will be in the same component.

If you are trying to access to a child component, you can use ref for accomplishing this task. More detailed information about ref is here

like image 184
talhadgrl Avatar answered Feb 01 '26 03:02

talhadgrl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!