> 文章列表 > Vue:(三十五)路由vue-router

Vue:(三十五)路由vue-router

Vue:(三十五)路由vue-router

今天,我们开始学习vue中一个很关键的知识点,路由

理解

vue的一个插件库,专门用来实现SPA应用

  1. 单页web应用

  1. 整个应用只有一个完整的页面

  1. 点击页面中的导航连接不会刷新页面,只会做页面的局部更新

  1. 数据需要通过ajax请求获取

下来,看一下工程结构:

Vue:(三十五)路由vue-router

这里注意一下,我们为了区分一般组件和路由组件,会统一把路由组件放在pages目录下。

首先,我们要先安装vue-router插件:npm -i vue-router,这里需要注意版本的问题

然后在main.js中导入并使用路由:

main.js

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
//引入路由器
import router from './router/index'//关闭Vue的生产提示
Vue.config.productionTip = false
Vue.use(VueRouter)
new Vue({render: h => h(App),router: router,
}).$mount('#app')

创建路由规则:

router/index.js

//该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
//引入组件
import About from '../pages/About.vue'
import Home from '../pages/Home.vue'//创建并暴露一个路由器
export default new VueRouter({routes: [{path: '/about',component: About,},{path: '/home',component: Home,},],
})

接下来创建路由组件:

About.vue

<template><div><h2>我是About</h2></div>
</template><script>export default {name: 'About',}
</script><style>
</style>

Home.vue

<template><div><h2>我是Home</h2></div>
</template><script>export default {name: 'Home',}
</script><style>
</style>

最后,在app.vue中引入并使用路由组件,进行相关的操作

App.vue

<template><div><div class="row"><Banner /></div><div class="row"><div class="col-xs-2 col-xs-offset-2"><div class="list-group"><router-link class="list-group-item" active-class="active"to="/about">About</router-link><router-link class="list-group-item" active-class="active"to="/home">Home</router-link></div></div><div class="col-xs-6"><div class="panel"><div class="panel-body"><router-view></router-view></div></div></div></div></div>
</template><script>import Banner from './components/Banner.vue'export default {name: 'App',components: { Banner },}
</script>

结果如下:

Vue:(三十五)路由vue-router

以上就是用过一个案例来使用vue-router。

我是空谷有来人,谢谢支持。