Vue-router 学习
环境搭建
输入命令
npm install vue-router --save-dev
简单代码
使用之前搭建好的环境项目
创建两个组件 实现在主界面切换使用
创建components文件夹存放组件
创建一个Content组件
<template>
<h1>内容</h1>
</template>
<script>
export default {
name: "Content"
}
</script>
<style scoped>
</style>
创建一个Main组件
<template>
<h1>首页</h1>
</template>
<script>
export default {
name: "Main"
}
</script>
<style scoped>
</style>
路由配置
创建一个router文件夹 编写一个index.js(规定这是配置文件)
import Vue from 'vue'
import VueRouter from 'vue-router'
import Content from '../components/Content'
import Main from '../components/Main'
Vue.use(VueRouter);
//配置导出路由
export default new VueRouter({
routes: [
{
//路由路径
path:'/content',
name:'content',
//跳转的组件
component:Content
},
{
//路由路径
path:'/main',
name:'main',
//跳转的组件
component:Main
}
]
});
在main.js中配置路由
import Vue from 'vue'
import App from './App'
import router from './router' //自动扫描index.js
Vue.config.productionTip = false
new Vue({
el: '#app',
//配置路由
router,
components: { App },
template: '<App/>'
})
在App.vue使用配置好的路由
<template>
<div id="app">
<h1>首页</h1>
<router-link to="/main">首页</router-link>
<router-link to="/content">内容</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>
效果:

根据点的连接切换不同的组件内容

浙公网安备 33010602011771号