[英]How to access a const inside a function in Vue?
我正在使用 Laravel/Inertia/Vue3,我得到了用户 object,然后我想在其他 function 中使用它,但它始终未定义。
<script setup>
// imports...
const props = defineProps({
// props...
})
const user = computed(() => usePage().props.value.user);
const click = () => {
alert(`${user.name} clicked`);
}
</script>
如果我尝试通过车把访问 HTML 中的user
object,它会按预期工作,但我不能在单击 function 中使用它。当然我可以在 function 中分配一个const user
,其值为usePage().props...
但这看起来很丑陋,必须有另一种方式。
当然,我是 Vue 的新手。
编辑 #####
当我说它看起来很丑时,我指的是这个:
<script setup>
// imports...
const props = defineProps({
// props...
})
const user = computed(() => usePage().props.value.user);
const click = () => {
const user = usePage().props.value.user;
alert(`${user.name} clicked`);
}
</script>
一定有更好更正确的方法
computed()
返回一个ref
,因此您的点击处理程序需要通过ref
的value
prop 展开值:
<script setup>
const user = computed(() => usePage().props.value.user);
const click = () => {
//alert(`${user.name} clicked`); ❌
alert(`${user.value.name} clicked`); ✅
}
</script>
或者,您可以避免使用<script setup>
中的Reactivity Transform展开(即本例中的$computed()
):
<script setup>
//const user = computed(() => usePage().props.value.user);
const user = $computed(() => usePage().props.value.user);
const click = () => {
alert(`${user.name} clicked`);
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.