เราสามารถเขียน method สำหรับการ validate ข้อมูลใน NuxtJS ได้ เช่นตัวอย่างนี้จะเป็นการตรวจสอบ params ที่ request ว่าให้เป็นตัวเลขเท่านั้น
pages/posts/_id/index.vue
<template>
    <h1>Posts page id {{$route.params.id}}</h1>
</template>
<script>
export default {
    validate(context) {
        return /^\d+$/.test(context.params.id)
    }
}
</script>
จากนั้นทดสอบเรียก url http://localhost:3000/posts/99 นั้นสามารถใช้ได้ปกติ แต่ถ้าพิมพ์ข้อความ http://localhost:3000/posts/test จะแสดง error
หรือสามารถใช้ params แทน context ได้ เช่น
<template>
    <h1>Posts page id {{$route.params.id}}</h1>
</template>
<script>
export default {
    validate({params}) {
        return /^\d+$/.test(params.id)
    }
}
</script>
 
                             
                        
ความคิดเห็น