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()?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With