vue-router
组件化控制视图跳转
1、安装vue-router
npm install vue-router --save-dev
如果安装过程中报了警告,仔细看后面会有提示信息,并给出了修复命令建议,按照建议命令执行即可
2、创建两个可供跳转的组件:
Main.vue
<template>
<h1>首页</h1>
</template>
<script>
export default {
name: "Main"
}
</script>
<style scoped>
</style>
Content.vue
<template>
<h1>内容页</h1>
</template>
<script>
export default {
name: "Comtent"
}
</script>
<style scoped>
</style>
结构如下:
3、创建router组件 index.js
index.js
import Vue from 'vue';
import VueRouter from 'vue-router';
//导入要跳转的vue组件
import Content from '../components/Content'
import Main from '../components/Main'
//安装路由
Vue.use(VueRouter);
export default new VueRouter({
routes:[
{
//路由路径(请求到path配置的路径后跳转到对应的组件)
path: '/content',
//跳转组件
component: Content
},
{
path: '/main',
component: Main
}
]
});
此时项目结构:
4、在App.vue中添加跳转组件的链接(取代了原来的a标签)
<template>
<div id="app">
<h1>Vue-Router</h1>
<router-link to="/main">首页</router-link>
<router-link to="/content">内容页</router-link>
//显示router跳转视图,搭配router-link一起使用
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
5、在全局唯一的Vue对象main.js文件中去扫描使用路由(index.js)
import Vue from 'vue'
import App from './App'
//会自动扫描./router下的index文件
import router from './router'
Vue.config.productionTip = false;
new Vue({
el: '#app',
//配置路由
router,
components: { App },
template: '<App/>'
});
6、启动项目,测试是否成功跳转
npm run dev