To effectively access data in Vue, one approach would involve importing the getCurrentInstance
function and utilizing it within the onMounted lifecycle or within a consumable:
import { onMounted, getCurrentInstance } from "vue";
export default {
data() {
return {
key: "test",
};
},
setup() {
onMounted(() => {
console.log(getCurrentInstance().data.key);
});
},
};
Nevertheless, this method is not recommended as indicated here.
Alternatively, you can define the data property in setup using ref or reactive like so:
import { ref } from "vue";
export default {
setup() {
const $localStorage = ref({});
},
};
or
import { reactive } from "vue";
export default {
setup() {
const $localStorage = reactive({});
},
};
These solutions are suitable when the data and setup function are within the same component.
If you need to access a child component, you can utilize ref
for this purpose. More information on ref
can be found here