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()?
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()?
Share Improve this question asked Jul 24, 2021 at 11:57 web pakistanweb pakistan 4941 gold badge6 silver badges25 bronze badges 3-
1
Inside
setup()
,this
won't be a reference to the current active instance Sincesetup()
is called before other ponent options are resolved,this
insidesetup()
will behave quite differently fromthis
in other options. This might cause confusions when usingsetup()
along other Options API. Please refer this for more details v3.vuejs/guide/position-api-setup.html#arguments – Sowmyadhar Gourishetty Commented Jul 24, 2021 at 12:34 - Can you also explain your use case? – Sowmyadhar Gourishetty Commented Jul 24, 2021 at 12:34
- as far as I know "this" isn't other options it is literally bound to undefined according to the Types in Vue. – Braks Commented Jul 26, 2021 at 12:54
2 Answers
Reset to default 7One 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 ponent.
If you are trying to access to a child ponent, you can use ref
for acplishing this task. More detailed information about ref
is here
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>