1.安装
//在项目里安装vue-router 保存配置到dev配置文件里
cnpm install vue-router --save-dev
2.使用
- 在初始的webpack项目中,创建组件
//路径
/components/main.vue
<template>
<html>
<div>首页</div>
</html>
</template>
<script>
/*组件名字*/
export default {
name: "main"
}
</script>
<!--scoped:style只在本组件生效-->
<style scoped>
</style>
/components/content.vue
<template>
<html>
<div>内容</div>
</html>
</template>
<script>
export default {
name: "content"
}
</script>
<style scoped>
</style>
- 在router下建立index.js配置相关路由
/*导入router*/
import Vue from 'vue';
import vueRouter from 'vue-router';
import content from "../components/content";
import main from "../components/main";
/*得先导入vue,开启router*/
Vue.use(vueRouter);
/*配置导出路由,所有路由可以放在这,在main中导入这个
* 一般默认路由配置在router/index.js中*/
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'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
- APP.vue组件中配置
<template>
<div id="app">
<router-link to="main">首页</router-link>
<router-link to="content">内容</router-link>
<!--展示组件内容-->
<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 . 命令行下:npm run dev
- 修改组件,热部署,自动部署
- 组件变化,只修改组件即可,模块化管理