路由
安装:
script引入方式:
<script src="/path/to/vue.js"></script>
<script src="/path/to/vue-router.js"></script>
npm方式:
npm install vue-router
引用:
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const router = new Router({
mode: 'history',
routes: [
{ path: '/',component: Home //path路由地址,component组件地址,上面需引入 },
{path: '/about',name:'路由名称',component: About},//通过name给路由定义名称
{path: '*',redirect:'/'}//找不到路由地址,跳转到首页
]
})
new Vue({
router
}) //实例化router
使用:
<div id="app">
<ul>
<li><router-link tag="div" to="/">Hello</router-link></li>
<li><router-link :to="{name:'路由名称'}">About</router-link></li>
</ul>
<router-view></router-view>
</div>
//router-link标签默认生成的是a标签,可以通过tag属性重新定义,如tag="div"
//:to可以通过路由name进行跳转
跳转
<router-link >第一种</router-link>
function(){
this.$router.push() //第二种,可以直接写路径,或者{name:'路由名称'}
}
二级路由创建
import Vue from 'vue'
import App from './App.vue'
import Router from 'vue-router'//引入
Vue.use(Router)
import Hello from './components/Hello'//一级路由
import About from './components/about/About'//一级路由
import Phone from './components/about/Phone'//二级路由
import Email from './components/about/Email'//二级路由
Vue.config.productionTip = false
const router = new Router({
mode: "history",//去掉域名地址上的#符号
routes: [
{ path: "/",name:'homeLink', component: Hello },//定义一级路由
{ path: "/about",redirect:'/about/phone', component: About,children:[//通过children设置二级路由,redirect设置默认路由
{path:"/about/phone",name:'phoneLink',component:Phone},
{path:"/about/email",name:'emailLink',component:Email}
]},
{ path: "*", redirect: "/about" }
]
})
new Vue({
router,//实例化router
render: h => h(App)
}).$mount('#app')
网友评论