Nuxt配置動態路由以及參數校驗


動態路由就是帶參數的路由。比如我們商品列表里很多商品詳細頁,這時候就需要動態路由的幫助了。

比如我們新建一個commodity文件夾,新建一個index.vue 文件,然后新建一個_id.vue (以下畫線為前綴的Vue文件就是動態路由,然后在文件里邊有 $route.params.id來接收參數)

index.vue (可以寫三種方式):

<a href="/commodity/123">commodity1</a>
<nuxt-link to="/commodity/123">commodity2</nuxt-link>
<nuxt-link :to="{name: 'commodity',params:{id: 123}}">commodity3</nuxt-link>  (推薦這種寫法)

_id.vue:

<h2>commodity-Content [{{$route.params.id}}]</h2>

 

校驗傳遞參數的正確性是很有必要的,Nuxt.js也貼心的為我們准備了校驗方法validate( )。

_id.vue:

export default {

  validate ({ params }) {
    // Must be a number
    return /^\d+$/.test(params.id)
  }

}

我們使用了validate方法,並把params傳遞進去,然后用正則進行了校驗,如果正則返回了true正常進入頁面,如果返回false進入404頁面

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM