【Vue 开发实战】生态篇 # 19:Vue Router的使用场景
原创
©著作权归作者所有:来自51CTO博客作者凯小默的博客的原创作品,请联系作者获取转载授权,否则将追究法律责任
说明
【Vue 开发实战】学习笔记。
传统开发模式
-
www.xxx.com
—— index.html -
www.xxx.com/about
—— about.html -
www.xxx.com/xxx
—— xxx.html
单页面(SPA)开发模式
-
www.xxx.com
—— index.html -
www.xxx.com/about
—— index.html -
www.xxx.com/xxx
—— index.html
解决的问题
- 监听 URL 的变化,并在变化前后执行相应的逻辑
- 不同的 URL 对应不同的不同的组件
- 提供多种方式改变 URL 的 API ( URL的改变不能导致浏览器刷新)
使用方式
- 提供一个路由配置表,不同 URL 对应不同组件的配置
- 初始化路由实例 new VueRouter()
- 挂载到 Vue 实例上
- 提供一个路由占位,用来挂载 URL 匹配到的组件
实战例子
完整的请看:https://github.com/kaimo313/vue-development-practice/tree/master/router-demo
router-demo\src\main.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
import routes from './routes'
Vue.config.productionTip = false
Vue.use(VueRouter)
const router = new VueRouter({
mode: 'history',
routes,
})
new Vue({
router,
render: h => h(App),
}).$mount('#app')
router-demo\src\routes.js
import RouterDemo from './components/RouterDemo'
import RouterChildrenDemo from './components/RouterChildrenDemo'
const routes = [
{ path: '/foo', component: RouterDemo, name: '1' },
{ path: '/bar', component: RouterDemo, name: '2' },
// 当 /user/:id 匹配成功,
// RouterDemo 会被渲染在 App 的 <router-view /> 中
{ path: '/user/:id',
component: RouterDemo,
name: '3',
props: true,
children: [
{
// 当 /user/:id/profile 匹配成功,
// RouterChildrenDemo 会被渲染在 RouterDemo 的 <router-view/> 中
path: 'profile',
component: RouterChildrenDemo,
name: '3-1'
},
{
// 当 /user/:id/posts 匹配成功
// RouterChildrenDemo 会被渲染在 RouterDemo 的 <router-view/> 中
path: 'posts',
component: RouterChildrenDemo
}
]
},
{ path: '/a', redirect: '/bar' },
{ path: '*', component: RouterDemo, name: '404' }
]
export default
router-demo\src\components\RouterDemo.vue
<template>
<div>
<router-link to="/foo">Go to Foo</router-link>
<br/>
<router-link to="/user/12">Go to /user/12</router-link>
<br/>
<router-link to="/user/12/profile">Go to /user/12/profile</router-link>
<br/>
<router-link to="/other">Go to 404</router-link>
<br/>
<router-link to="/a">Go to a 重定向到 bar</router-link>
<br/>
<a href="#/foo">Go to Foo</a>
<br/>
<button @click="$router.push('foo')">Go to Foo</button>
<p>id: {{id}}</p>
<p>{{routerInfo}}</p>
<router-view></router-view>
</div>
</template>
<script>export default {
props: ['id'],
computed: {
routerInfo() {
const { fullPath, path, name, params, query, meta } = this.$route
return {
fullPath, path, name, params, query, meta
}
}
}
}</script>
router-demo\src\components\RouterChildrenDemo.vue
<template>
<div>
{{routerInfo}}
</div>
</template>
<script>export default {
computed: {
routerInfo() {
const { fullPath, path, name, params, query, meta } = this.$route
return {
fullPath, path, name, params, query, meta
}
}
}
}</script>
效果如下: