使用2.x来进行创建项目:
安装vue-router的依赖:
运行项目:npm run dev
生成的项目目录:
步骤:
1、创建组件
2、配置路由
3、创建路由对象
4、注入
新建几个:
创建组件:
Home.vue
<!--创建组件--> <template> <div class="home"> <h1>首页在这里</h1> </div> </template>
Foods.vue
<!--创建组件--> <template> <h1>美食广场</h1> </template>
配置路由:
routers.js
import Home from './views/Home.vue' import Foods from './views/Foods.vue' //配置路由 export default{ routes: [ { path:'/home', component:Home }, { path:'/foods', component:Foods } ] }
创建路由对象:
import Routers from './routers.js' Vue.use(VueRouter) //创建路由对象 const router=new VueRouter(Routers)
注入:
new Vue({ el: '#app', //注入 router, render: h => h(App) })
App.vue
1 <template> 2 <div id="app"> 3 <img src="./assets/logo.png"><br/> 4 5 <router-link to='/home'>首页</router-link> 6 <router-link to='/foods'>美食</router-link> 7 8 <router-view> </router-view> 9 10 11 12 </div> 13 </template> 14 15 <script> 16 export default { 17 name: 'app', 18 data () { 19 return { 20 msg: 'Welcome to Your Vue.js App' 21 } 22 } 23 } 24 </script> 25 26 <style> 27 #app { 28 font-family: 'Avenir', Helvetica, Arial, sans-serif; 29 -webkit-font-smoothing: antialiased; 30 -moz-osx-font-smoothing: grayscale; 31 text-align: center; 32 color: #2c3e50; 33 margin-top: 60px; 34 } 35 36 h1, h2 { 37 font-weight: normal; 38 } 39 40 ul { 41 list-style-type: none; 42 padding: 0; 43 } 44 45 li { 46 display: inline-block; 47 margin: 0 10px; 48 } 49 50 a { 51 color: #42b983; 52 } 53 </style>
在浏览器中显示的效果: