web pakistan
web pakistan

Reputation: 494

'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()?

Upvotes: 15

Views: 16359

Answers (2)

Tipa Stephen
Tipa Stephen

Reputation: 11

Do not forget to return the property from the setup method, if not using

<script setup></script>

as stated in the Official Documentation

<script>
import {ref} from "vue";

export default {
  name: "Demo",
  data: () => ({
    $localStorage: {}
  }),
  setup() {
    // make it reactive
    const $localStorage = ref({})
    
    // Finally return the property
    return {$localStorage}
  }
}
</script>

Upvotes: 0

talhadgrl
talhadgrl

Reputation: 96

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

Upvotes: 7

Related Questions