10、Vue:实战快速上手

tech2022-07-30  145

文章目录

10.1、创建工程10.2、创建登录页面10.3、嵌套路由10.4、参数传递10.5、重定向10.6、重定向10.7、路由模式与40410.7.1、处理40410.7.2、路由钩子与异步请求 我们采用实战教学模式并结合 ElementUI 组件库,将所需知识点应用到实际中,以最快速度带领大家掌握Vue的使用;

10.1、创建工程

注意: 命令行都要使用管理员模式运行(出错的情况下)

创建一个名为hello-vue的工程 vue init webpack hello-vue安装依赖,我们需要安装 vue-router、element-ui、sass-loader 和 node-sass 四个插件 # 进入工程目录 cd hello-vue # 安装 vue-router npm install vue-router --save-dev # 安装 element-ui npm i element-ui -S # 安装依赖 npm install # 安装SASS加载器 cnpm install sass-loader node-sass --save-dev # 启动测试 npm run dev Npm命令解释 npm install moduleName:安装模块到项目目录下nom install -g moduleName:-g 的意思是将模块安装到全局,具体安装到哪个位置,要看 npm config prefix的位置npm install -save moduleName:-save 的意思是将模块安装到项目目录下,并在package文件的dependencies节点写入依赖,-S 为该命令的缩写npm install --save -dev moduleName:–save-dev的意思是将模块安装到项目目录下,并在package文件的devDependencies 节点写入依赖,-D 为该命令的缩写

10.2、创建登录页面

把没有用的东西删掉

在源码目录中创建如下结构:

assects:用于存放资源文件components:用于存放Vue功能组件views:用于存放Vue视图组件routrer:用于存放vue-router 配置 创建首页视图,在views目录下创建一个名为Main.vue的视图组件 <template> <h1>首页</h1> </template> <script> export default { name: "Main" } </script> <style scoped> </style>

创建登录页视图在views目录下创建一个名为Login.vue的视图组件,其中 el- 的元素为ElementUI组件*

<template> <div> <el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box"> <h3 class="login-title">欢迎登录</h3> <el-form-item label="账号" prop="username"> <el-input type="text" placeholder="请输入账号" v-model="form.username"/> </el-form-item> <el-form-item label="密码" prop="password"> <el-input type="password" placeholder="请输入密码" v-model="form.password"/> </el-form-item> <el-form-item> <el-button type="primary" v-on:click="onSubmit('loginForm')">登录</el-button> </el-form-item> </el-form> <el-dialog title="温馨提示" :visible.sync="dialogVisible" width="30%" :before-close="handleClose"> <span>请输入账号和密码</span> <span slot="footer" class="dialog-footer"> <el-button type="primary" @click="dialogVisible = false">确 定</el-button> </span> </el-dialog> </div> </template> <script> export default { name: "Login", data() { return { form: { username: '', password: '' }, // 表单验证,需要在 el-form-item 元素中增加 prop 属性 rules: { username: [ {required: true, message: '账号不可为空', trigger: 'blur'} ], password: [ {required: true, message: '密码不可为空', trigger: 'blur'} ] }, // 对话框显示和隐藏 dialogVisible: false } }, methods: { onSubmit(formName) { // 为表单绑定验证功能 this.$refs[formName].validate((valid) => { if (valid) { // 使用 vue-router 路由到指定页面,该方式称之为编程式导航 this.$router.push("/main"); } else { this.dialogVisible = true; return false; } }); } } } </script> <style lang="scss" scoped> .login-box { border: 1px solid #DCDFE6; width: 350px; margin: 180px auto; padding: 35px 35px 15px 35px; border-radius: 5px; -webkit-border-radius: 5px; -moz-border-radius: 5px; box-shadow: 0 0 25px #909399; } .login-title { text-align: center; margin: 0 auto 40px auto; color: #303133; } </style>

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

import Vue from 'vue' import Router from 'vue-router' import Main from "../views/Main"; import Login from "../views/Login"; Vue.use(Router); export default new Router({ routes: [ { path: '/main', component: Main }, { path: '/login', component: Login } ] })

main.js是index.html调用的 所以前面注册的组件要在这里导入,一定不要忘记扫描路由配置并将其用到new Vue中 main.js:

import Vue from 'vue' import App from './App' import Router from './router' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(Router) Vue.use(ElementUI) new Vue({ el: '#app', Router, // 问题点 render: h => h(App) //elementUI })

注意点:

我在vue实例中,使用对象属性简写形式加入了自命名的路由属性,但vue需要识别固定属性名router以加载vue-router

解决方法:

所以,如果引入路由组件时,使用自定义名称,在vue实例中声明时,应以键值对形式引入,如下

new Vue({ el: '#app', router: mRouter, components: { App }, template: '<App/>' })

或者干脆别折腾,以常规的router命名的对象简写形式引入

import router from './router' new Vue({ el: '#app', router, components: { App }, template: '<App/>' })

在App.vue中配置显示视图

<template> <div id="app"> <router-link to="/login">login</router-link> <router-link to="/main">main</router-link> <router-view></router-view> </div> </template> <script> export default { name: 'App', } </script>

问题:当我们执行npm run dev时,报错如下

或许是package.json文件中的sass-loader版本太高,降级成7.3.1,然后cnpm install后再次执行npm run dev

如果还是存在问题,顺序执行 npm rebuild node-sass npm update cnpm install npm run dev

测试成功! 访问:http://localhost:8080/#/ 点击login查看

10.3、嵌套路由

嵌套路由又称为子路由,在实际应用中,通常由多层嵌套的组件组合而成,同样地,URL中各段动态路径也按某种结构对应嵌套地各个组件,例如:

用户信息组件,在 views/user目录下创建一个名为Profile.vue地视图组件; <template> <h1>个人信息</h1> </template> <script> export default { name: "UserProfile" // 可以手动修改名字 } </script> <style scoped> </style> 用户信息组件,在 views/user目录下创建一个名为List.vue地视图组件; <template> <h1>用户列表</h1> </template> <script> export default { name: "List" } </script> <style scoped> </style> 配置嵌套路由修改router目录下地index.js路由配置文件,代码如: import Vue from 'vue' import Router from 'vue-router' import Main from "../views/Main"; import Login from "../views/Login"; import UserList from "../views/user/List"; import UserProfile from "../views/user/Profile"; Vue.use(Router); export default new Router({ routes: [ { path: '/main', component: Main, // 嵌套路由 children: [ { path: '/user/profile',component: UserProfile, }, { path: '/user/list',component: UserList, } ] }, { path: '/login', component: Login, } ] })

说明:主要是在路由配置中增加了children数组配置,用于在该组件下设置嵌套路由

修改首页视图,我们修改Main.vue视图组件,此处使用了ElementUI布局容器组件,代码如下: <template> <div> <el-container> <el-aside width="200px"> <el-menu :default-openeds="['1']"> <el-submenu index="1"> <template slot="title"><i class="el-icon-caret-right"></i>用户管理</template> <el-menu-item-group> <el-menu-item index="1-1"> <!--插入的地方--> <router-link to="/user/profile">个人信息</router-link> </el-menu-item> <el-menu-item index="1-2"> <!--插入的地方--> <router-link to="/user/list">用户列表</router-link> </el-menu-item> </el-menu-item-group> </el-submenu> <el-submenu index="2"> <template slot="title"><i class="el-icon-caret-right"></i>内容管理</template> <el-menu-item-group> <el-menu-item index="2-1">分类管理</el-menu-item> <el-menu-item index="2-2">内容列表</el-menu-item> </el-menu-item-group> </el-submenu> </el-menu> </el-aside> <el-container> <el-header style="text-align: right; font-size: 12px"> <el-dropdown> <i class="el-icon-setting" style="margin-right: 15px"></i> <el-dropdown-menu slot="dropdown"> <el-dropdown-item>个人信息</el-dropdown-item> <el-dropdown-item>退出登录</el-dropdown-item> </el-dropdown-menu> </el-dropdown> </el-header> <el-main> <!--在这里展示视图--> <router-view /> </el-main> </el-container> </el-container> </div> </template> <script> export default { name: "Main" } </script> <style scoped lang="scss"> .el-header { background-color: #B3C0D1; color: #333; line-height: 60px; } .el-aside { color: #333; } </style> 效果

10.4、参数传递

10.5、重定向

前端传递参数

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

<!--name:传组件名 params:传递参数,需要绑定对象:v-bind--> <router-link v-bind:to="{name: 'UserProfile', params: {id: 1}}">个人信息</router-link> 修改路由配置,增加props:true属性

​ 主要是router下的index.js中的 path 属性中增加了 :id 这样的占位符

{ path: '/user/profile/:id', name: 'UserProfile', component: UserProfile, props:true } 前端显示

在要展示的组件Profile.vue中接收参数

Profile.vue:

<template> <div> <h1>个人信息</h1> <h1>{{id}}</h1> </div> </template> <script> export default { props: ['id'], name: "UserProfile" } </script> <style scoped> </style>

注意:template标签中只能有一个跟标签,所以我们需要在template标签里写一个div标签,然后再div标签中实现

运行

10.6、重定向

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

{ path: '/main', name: 'Main', component: Main }, { path: '/goHome', redirect: '/main' }

说明:这里定义了两个路径,一个是/main,一个是/goHome,其中/goHome重定向到了/main路径,由此可以看出重定向不需要定义组件; 使用的话,只需要设置对应路径即可;

<el-menu-item index="1-3"> <!--插入的地方--> <router-link to="/goHome">回到首页</router-link> </el-menu-item>

10.7、路由模式与404

路由模式有两种

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

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

export default new Router({ mode:'history', routes: [ ] })

10.7.1、处理404

创建一个NotFound.vue视图组件 <template> <div> <h1>404,你的页面走丢了</h1> </div> </template> <script> export default { name: "NotFound" } </script> <style scoped> </style> 修改路由配置,代码如下: import NotFound from "../views/NotFound"; { path:'/*', component: NotFound, }

10.7.2、路由钩子与异步请求

beforeRouteEnter:在进入路由前执行

beforeRouteLeave:在离开路由前执行

在Profile.vue中写:

export default { props: ['id'], name: "UserProfile", beforeRouteEnter:(to,from,next)=> { console.log("进入路由之前"); next(); }, beforeRouteLeave:(to,form,next)=>{ console.log("离开路由之前") next(); } }

参数说明

to:路由将要跳转的路径信息

from:路由跳转前的路径信息

next:路由的控制参数

next() 跳入下一个页面next(’/path’)改变路由的跳转方向,使其跳到另一个路由next(false) 返回原来的页面next((vm)=>{}) 仅在beforeRouteEnter 中可用,vm是组件实例

在钩子函数中使用异步请求

安装Axios cnpm install axios -smain.js引用Axios import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios, axios) 准备数据 : 只有我们的 static 目录下的文件是可以被访问到 的,所以我们就把静态文件放入该目录下。 数据和之前用的json数据一样 需要的去上述axios例子里 // 静态数据存放的位置 static/mock/data.json 在 beforeRouteEnter 中进行异步请求

Profile.vue:

export default { props: ['id'], name: "UserProfile", beforeRouteEnter:(to,from,next)=> { console.log("进入路由之前"); // 加载数据 next(vm =>{ vm.getData(); // 进入路由之前执行getData }); }, beforeRouteLeave:(to,form,next)=>{ console.log("离开路由之前") next(); }, methods: { getData: function() { this.axios({ method: 'get', url: 'http://localhost:8080/static/mock/data.json', }).then(function (response) { console.log(response); }); } } } 测试执行

学习视频链接:https://www.bilibili.com/video/BV18E411a7mC?p=16

最新回复(0)