Nuxt 巢狀路由nuxt-child元件用法(父子頁面元件的傳值)
Nuxt巢狀路由官網上的API詳解:點選連結
看了官網上的api實現了官網的案例你會發現訪問父頁面中只能顯示父頁面中的內容,要想預設的在<nuxt-child>區域顯示一個頁面內容怎麼辦?
自己案例程式碼:
pages/parent.vue
<template> <div> <h2>父元件的頁面的內容</h2> <ul> <!-- 進行切換子頁面,寫法同vue.js --> <li><nuxt-link to='/parent/child'>child</nuxt-link></li> <li><nuxt-link to='/parent/child2'>child2</nuxt-link></li> </ul> <hr> <div class="box"> <p>巢狀子頁面內容區</p> <!-- <nuxt-child>標籤在父頁面元件中相當於是子頁面元件的佔位符;巢狀中這個不可少 --> <nuxt-child keep-alive :foobar="123"></nuxt-child> </div> </div> </template> <script> export default { } </script> <style scoped> .box{ margin-top: 20px; padding: 20px; border: 2px solid pink; border-radius: 5px; } </style>
pages/parent/index.vue
<template> <div> <h2>巢狀子元件中的預設頁面index.vue</h2> </div> </template> <script> export default { } </script> <style scoped> </style>
pages/parent/child.vue
<template> <div> <h2>巢狀子元件中的頁面child</h2> <p>foobar:{{foobar}}</p> </div> </template> <script> export default { props:['foobar'] } </script> <style scoped> </style>
pages/parent/child2.vue
<template> <div> <h2>巢狀子元件中的頁面child2</h2> <p>foobar:{{foobar}}</p> </div> </template> <script> export default { props: ['foobar'] } </script> <style scoped> </style>
效果如下:
補充知識:nuxt二級路由
耗費了大半天的時間,終於把頁面的二級路由配置好了
先看我的目錄
如果沒有登陸頁,根本就不用考慮巢狀路由的問題,主要的menu跳轉和<nuxt />可以直接寫到layouts/default.vue中,首頁可以放到pages/index.vue,就可以了。
好了,步入核心的
情景,在中介軟體middleware/authenticated.js
// 定義了一箇中間件, 如果使用者未登入, 則跳轉登入頁。 export default function ({ store,redirect }) { if (!store.state.user) { return redirect('/login') } }
首先,需要知道,pages/index.vue這個檔案必須有,這是給路由'/',定義的頁面,但是我真正的首頁是在user/index.vue
pages/index.vue下
<template> <div style="height:100%;"> </div> </template> <script> export default { created () { console.log(this.$router) this.$router.push('/login') // 頁面載入時跳轉 } } </script>
意思是載入二級路由的pages/users.vue頁面
<template> <div style="height:100%;"> <el-container style="height:100%"> <el-header class="theme-bg-color"> <my-head /> </el-header> <el-container style="height:100%;"> <my-side /> <el-main> <NuxtChild :key="key"/> </el-main> </el-container> </el-container> </div> </template>
<script> import MySide from '~/components/MySide.vue' import MyHead from '~/components/MyHead.vue' export default { components: { MySide,MyHead },computed: { key() { return this.$route.name !== undefined? this.$route.name +new Date(): this.$route +new Date() } } } </script>
注意,在pages/users/index.vue頁面中
export default { name: 'users' }
其他頁面,比如pages/users/ditch.vue頁面中
export default { name: 'users-ditch' }
一定要這樣去寫name,官網上也是這樣說明的。
總結,巢狀路由(二級路由寫法)
一,頁面有個user.vue,資料夾也要有個同名的user;
二,最好有index.vue頁面;
三,name格式。
原始碼地址:
https://github.com/besswang/rj-payadmin-nuxt
以上這篇Nuxt 巢狀路由nuxt-child元件用法(父子頁面元件的傳值)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。