vue-router Hello World

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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值