Vue.js——路由1
使用路由,首先要下载路由 进入cmd然后层层进入项目
npm install vue-router --save
重新运行一下
npm run dev
准备工作做好了 接下来在main.js中配置一下你的路由信息
// 引入路由
import VueRouter from 'vue-router'
// 引入跳转的目标文件 这里用的都是组件
import Home from './components/Home'
import Menu from './components/Menu'
import About from './components/about/About'
// 使用路由
Vue.use(VueRouter)
// 声明路由信息 start
const routes=[
{path:'/',component:Home},
{path:'/menu',component:Menu},
{path:'/about',component:About},
{path:'*',redirect:'/'}
]
//或者使用name
const routes=[
{path:'/',name:"homeLink",component:Home},
{path:'/menu',name:"menuLink",component:Menu},
{path:'/about',name:"aboutLink",component:About},
{path:'*',redirect:'/'}
]
// 初始化路由
const router=new VueRouter({
routes,
mode:"history"
})
// 实例化对象中放入配置好的路由
new Vue({
el: '#app',
router,
render: h => h(App)
})
配置好了之后 在App.vue中使用
<router-view></router-view>
在需要跳转的地方 使用 router-link 替换a标签 to替换 href
<router-link to="/" class="nav-link">主页</router-link>
<router-link to="/menu" class="nav-link">菜单</router-link>
<router-link to="/about" class="nav-link">关于我们</router-link>
//或者使用name
<router-link :to="{name:'homeLink'}" class="nav-link">主页</router-link>
<router-link :to="{name:'menuLink'}" class="nav-link">菜单</router-link>
<router-link :to="{name:'aboutLink'}" class="nav-link">关于我们</router-link>
二级路由 添加children
const routes=[
{path:'/',name:"homeLink",component:Home},
{path:'/menu',component:Menu},
{path:'/about',redirect:'/history',component:About,
children:[
{path:'/about/contact',name:"contactLink",component:Contact},
{path:'/history',name:"historyLink",component:History},
{path:'/Delivery',name:"deliveryLink",component:Delivery},
{path:'/orderingGuide',name:"orderingGuideLink",component:OrderingGuide},
]},
{path:'*',redirect:'/'}
]