根据之前创建vue-cli项目一样再来一遍 创建项目
1. 创建一个名为 hello-vue 的工程 vue init webpack hello-vue
2. 安装依赖,我们需要安装 vue-router、element-ui、sass-loader 和 node-sass 四个插件

  1. # 进入工程目录
  2. cd hello-vue
  3. # 安装 vue-router
  4. npm install vue-router --save-dev
  5. # 安装 element-ui
  6. npm i element-ui -S
  7. # 安装依赖
  8. npm install
  9. # 安装 SASS 加载器
  10. cnpm install sass-loader node-sass --save-dev
  11. # 启动测试
  12. npm run dev

 创建成功后用idea打开,并删除净东西 创建views和router文件夹用来存放视图和路由

 

 在views创建Main.vue
Main.vue

  1. <template>
  2. <h1>首页</h1>
  3. </template>
  4. <script>
  5. export default {
  6. name: "Main"
  7. }
  8. </script>
  9. <style scoped>
  10. </style>

在views中创建Login.vue视图组件
Login.vue(用的饿了么UI中的代码)

  1. <template>
  2. <div>
  3. <el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">
  4. <h3 class="login-title">欢迎登录</h3>
  5. <el-form-item label="账号" prop="username">
  6. <el-input type="text" placeholder="请输入账号" v-model="form.username"/>
  7. </el-form-item>
  8. <el-form-item label="密码" prop="password">
  9. <el-input type="password" placeholder="请输入密码" v-model="form.password"/>
  10. </el-form-item>
  11. <el-form-item>
  12. <el-button type="primary" v-on:click="onSubmit('loginForm')">登录</el-button>
  13. </el-form-item>
  14. </el-form>
  15. <el-dialog
  16. title="温馨提示"
  17. :visible.sync="dialogVisible"
  18. width="30%"
  19. :before-close="handleClose">
  20. <span>请输入账号和密码</span>
  21. <span slot="footer" class="dialog-footer">
  22. <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  23. </span>
  24. </el-dialog>
  25. </div>
  26. </template>
  27. <script>
  28. export default {
  29. name: "Login",
  30. data() {
  31. return {
  32. form: {
  33. username: '',
  34. password: ''
  35. },
  36. // 表单验证,需要在 el-form-item 元素中增加 prop 属性
  37. rules: {
  38. username: [
  39. {required: true, message: '账号不可为空', trigger: 'blur'}
  40. ],
  41. password: [
  42. {required: true, message: '密码不可为空', trigger: 'blur'}
  43. ]
  44. },
  45. // 对话框显示和隐藏
  46. dialogVisible: false
  47. }
  48. },
  49. methods: {
  50. onSubmit(formName) {
  51. // 为表单绑定验证功能
  52. this.$refs[formName].validate((valid) => {
  53. if (valid) {
  54. // 使用 vue-router 路由到指定页面,该方式称之为编程式导航
  55. this.$router.push("/main");
  56. } else {
  57. this.dialogVisible = true;
  58. return false;
  59. }
  60. });
  61. }
  62. }
  63. }
  64. </script>
  65. <style lang="scss" scoped>
  66. .login-box {
  67. border: 1px solid #DCDFE6;
  68. width: 350px;
  69. margin: 180px auto;
  70. padding: 35px 35px 15px 35px;
  71. border-radius: 5px;
  72. -webkit-border-radius: 5px;
  73. -moz-border-radius: 5px;
  74. box-shadow: 0 0 25px #909399;
  75. }
  76. .login-title {
  77. text-align: center;
  78. margin: 0 auto 40px auto;
  79. color: #303133;
  80. }
  81. </style>

创建路由,在 router 目录下创建一个名为 index.js 的 vue-router 路由配置文件
index.js

  1. //导入vue
  2. import Vue from 'vue';
  3. import VueRouter from 'vue-router';
  4. //导入组件
  5. import Main from "../views/Main";
  6. import Login from "../views/Login";
  7. //使用
  8. Vue.use(VueRouter);
  9. //导出
  10. export default new VueRouter({
  11. routes: [
  12. {
  13. //登录页
  14. path: '/main',
  15. component: Main
  16. },
  17. //首页
  18. {
  19. path: '/login',
  20. component: Login
  21. },
  22. ]
  23. })

在main.js中配置相关
main.js main.js是index.html调用的 所以基本上所有东西都导出到这
一定不要忘记扫描路由配置并将其用到new Vue中

  1. import Vue from 'vue'
  2. import App from './App'
  3. import VueRouter from "vue-router";
  4. //扫描路由配置
  5. import router from "./router"
  6. //导入elementUI
  7. import ElementUI from "element-ui"
  8. //导入element css
  9. import 'element-ui/lib/theme-chalk/index.css'
  10. //使用
  11. Vue.use(VueRouter)
  12. Vue.use(ElementUI)
  13. Vue.config.productionTip = false
  14. new Vue({
  15. el: '#app',
  16. router,
  17. render: h => h(App),//ElementUI规定这样使用
  18. })

在App.vue中配置显示视图
App.vue

  1. <template>
  2. <div id="app">
  3. <!--展示视图-->
  4. <router-view></router-view>
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. name: 'App',
  10. }
  11. </script>

最后效果:

 

 

如果出现错误: 可能是因为sass-loader的版本过高导致的编译错误,当前最高版本是8.0.2,需要退回到7.3.1 ;
去package.json文件里面的 “sass-loader”的版本更换成7.3.1,然后重新cnpm install就可以了;

嵌套路由又称子路由,在实际应用中,通常由多层嵌套的组件组合而成。
demo
1、 创建用户信息组件,在 views/user 目录下创建一个名为 Profile.vue 的视图组件;
Profile.vue

  1. <template>
  2. <h1>个人信息</h1>
  3. </template>
  4. <script>
  5. export default {
  6. name: "UserProfile"
  7. }
  8. </script>
  9. <style scoped>
  10. </style>

在用户列表组件在 views/user 目录下创建一个名为 List.vue 的视图组件;
List.vue

  1. <template>
  2. <h1>用户列表</h1>
  3. </template>
  4. <script>
  5. export default {
  6. name: "UserList"
  7. }
  8. </script>
  9. <style scoped>
  10. </style>

修改首页视图,我们修改 Main.vue 视图组件,此处使用了 ElementUI 布局容器组件,代码如下:
Main.vue

  1. <template>
  2. <div>
  3. <el-container>
  4. <el-aside width="200px">
  5. <el-menu :default-openeds="['1']">
  6. <el-submenu index="1">
  7. <template slot="title"><i class="el-icon-caret-right"></i>用户管理</template>
  8. <el-menu-item-group>
  9. <el-menu-item index="1-1">
  10. <!--插入的地方-->
  11. <router-link to="/user/profile">个人信息</router-link>
  12. </el-menu-item>
  13. <el-menu-item index="1-2">
  14. <!--插入的地方-->
  15. <router-link to="/user/list">用户列表</router-link>
  16. </el-menu-item>
  17. </el-menu-item-group>
  18. </el-submenu>
  19. <el-submenu index="2">
  20. <template slot="title"><i class="el-icon-caret-right"></i>内容管理</template>
  21. <el-menu-item-group>
  22. <el-menu-item index="2-1">分类管理</el-menu-item>
  23. <el-menu-item index="2-2">内容列表</el-menu-item>
  24. </el-menu-item-group>
  25. </el-submenu>
  26. </el-menu>
  27. </el-aside>
  28. <el-container>
  29. <el-header style="text-align: right; font-size: 12px">
  30. <el-dropdown>
  31. <i class="el-icon-setting" style="margin-right: 15px"></i>
  32. <el-dropdown-menu slot="dropdown">
  33. <el-dropdown-item>个人信息</el-dropdown-item>
  34. <el-dropdown-item>退出登录</el-dropdown-item>
  35. </el-dropdown-menu>
  36. </el-dropdown>
  37. </el-header>
  38. <el-main>
  39. <!--在这里展示视图-->
  40. <router-view />
  41. </el-main>
  42. </el-container>
  43. </el-container>
  44. </div>
  45. </template>
  46. <script>
  47. export default {
  48. name: "Main"
  49. }
  50. </script>
  51. <style scoped lang="scss">
  52. .el-header {
  53. background-color: #B3C0D1;
  54. color: #333;
  55. line-height: 60px;
  56. }
  57. .el-aside {
  58. color: #333;
  59. }
  60. </style>

配置嵌套路由修改 router 目录下的 index.js 路由配置文件,使用children放入main中写入子模块,代码如下
index.js

  1. //导入vue
  2. import Vue from 'vue';
  3. import VueRouter from 'vue-router';
  4. //导入组件
  5. import Main from "../views/Main";
  6. import Login from "../views/Login";
  7. //导入子模块
  8. import UserList from "../views/user/List";
  9. import UserProfile from "../views/user/Profile";
  10. //使用
  11. Vue.use(VueRouter);
  12. //导出
  13. export default new VueRouter({
  14. routes: [
  15. {
  16. //登录页
  17. path: '/main',
  18. component: Main,
  19. // 写入子模块
  20. children: [
  21. {
  22. path: '/user/profile',
  23. component: UserProfile,
  24. }, {
  25. path: '/user/list',
  26. component: UserList,
  27. },
  28. ]
  29. },
  30. //首页
  31. {
  32. path: '/login',
  33. component: Login
  34. },
  35. ]
  36. })

路由嵌套实战效果图

 

 

这里演示如果请求带有参数该怎么传递
demo
用的还是上述例子的代码 修改一些代码 这里不放重复的代码了
第一种取值方式
1、 修改路由配置, 主要是router下的index.js中的 path 属性中增加了 :id 这样的占位符

  1. {
  2. path: '/user/profile/:id',
  3. name:'UserProfile',
  4. component: UserProfile
  5. }

2.传递参数
 此时我们在Main.vue中的route-link位置处 to 改为了 :to,是为了将这一属性当成对象使用,注意 router-link 中的 name 属性名称 一定要和 路由中的 name 属性名称 匹配,因为这样 Vue 才能找到对应的路由路径;

  1. <!--name是组件的名字 params是传的参数 如果要传参数的话就需要用v:bind:来绑定-->
  2. <router-link :to="{name:'UserProfile',params:{id:1}}">个人信息</router-link>

3.在要展示的组件Profile.vue中接收参数 使用 {{$route.params.id}}来接收
Profile.vue 部分代码

  1. <template>
  2. <!-- 所有的元素必须在根节点下-->
  3. <div>
  4. <h1>个人信息</h1>
  5. {{$route.params.id}}
  6. </div>
  7. </template>

第二种取值方式 使用props 减少耦合
1、修改路由配置 , 主要在router下的index.js中的路由属性中增加了 props: true 属性

  1. {
  2. path: '/user/profile/:id',
  3. name:'UserProfile',
  4. component: UserProfile,
  5. props: true
  6. }

2.传递参数和之前一样 在Main.vue中修改route-link地址

  1. <!--name是组件的名字 params是传的参数 如果要传参数的话就需要用v:bind:来绑定-->
  2. <router-link :to="{name:'UserProfile',params:{id:1}}">个人信息</router-link>

3.在Profile.vue接收参数为目标组件增加 props 属性
Profile.vue

  1. <template>
  2. <div>
  3. 个人信息
  4. {{ id }}
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. props: ['id'],
  10. name: "UserProfile"
  11. }
  12. </script>
  13. <style scoped>
  14. </style>

 

 

重定向的意思大家都明白,但 Vue 中的重定向是作用在路径不同但组件相同的情况下,比如:
在router下面index.js的配置

  1. {
  2. path: '/main',
  3. name: 'Main',
  4. component: Main
  5. },
  6. {
  7. path: '/goHome',
  8. redirect: '/main'
  9. }

说明:这里定义了两个路径,一个是 /main ,一个是 /goHome,其中 /goHome 重定向到了 /main 路径,由此可以看出重定向不需要定义组件;

使用的话,只需要在Main.vue设置对应路径即可;

  1. <el-menu-item index="1-3">
  2. <router-link to="/goHome">回到首页</router-link>
  3. </el-menu-item>

路由模式有两种

  • hash:路径带 # 符号,如 http://localhost/#/login
  • history:路径不带 # 符号,如 http://localhost/login

修改路由配置,代码如下:

  1. export default new Router({
  2. mode: 'history',
  3. routes: [
  4. ]
  5. });

404 demo
1.创建一个NotFound.vue视图组件
NotFound.vue

  1. <template>
  2. <div>
  3. <h1>404,你的页面走丢了</h1>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. name: "NotFound"
  9. }
  10. </script>
  11. <style scoped>
  12. </style>

修改路由配置index.js

  1. import NotFound from '../views/NotFound'
  2. {
  3. path: '*',
  4. component: NotFound
  5. }

效果图

 

 

beforeRouteEnter:在进入路由前执行
beforeRouteLeave:在离开路由前执行

在Profile.vue中写

  1. export default {
  2. name: "UserProfile",
  3. beforeRouteEnter: (to, from, next) => {
  4. console.log("准备进入个人信息页");
  5. next();
  6. },
  7. beforeRouteLeave: (to, from, next) => {
  8. console.log("准备离开个人信息页");
  9. next();
  10. }
  11. }

参数说明:
to:路由将要跳转的路径信息
from:路径跳转前的路径信息
next:路由的控制参数
next() 跳入下一个页面
next(’/path’) 改变路由的跳转方向,使其跳到另一个路由
next(false) 返回原来的页面
next((vm)=>{}) 仅在 beforeRouteEnter 中可用,vm 是组件实例

1、安装 Axios

  1. cnpm install --save vue-axios

main.js引用 Axios

  1. import axios from 'axios'
  2. import VueAxios from 'vue-axios'
  3. Vue.use(VueAxios, axios)

准备数据 : 只有我们的 static 目录下的文件是可以被访问到的,所以我们就把静态文件放入该目录下。
数据和之前用的json数据一样 需要的去上述axios例子里

  1. // 静态数据存放的位置
  2. static/mock/data.json

在 beforeRouteEnter 中进行异步请求
Profile.vue

  1. export default {
  2. //第二种取值方式
  3. // props:['id'],
  4. name: "UserProfile",
  5. //钩子函数 过滤器
  6. beforeRouteEnter: (to, from, next) => {
  7. //加载数据
  8. console.log("进入路由之前")
  9. next(vm => {
  10. //进入路由之前执行getData方法
  11. vm.getData()
  12. });
  13. },
  14. beforeRouteLeave: (to, from, next) => {
  15. console.log("离开路由之前")
  16. next();
  17. },
  18. //axios
  19. methods: {
  20. getData: function () {
  21. this.axios({
  22. method: 'get',
  23. url: 'http://localhost:8080/static/mock/data.json'
  24. }).then(function (response) {
  25. console.log(response)
  26. })
  27. }
  28. }
  29. }

路由钩子和axios结合图

版权声明:本文为xiaofengzai原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/xiaofengzai/p/14956317.html