VUE —— 9、路由(二级路由、路由拦截)、axios

小咪咪 2022-08-29 12:54 372阅读 0赞

目录

8.二级路由

(1)路由配置

(2)二级路由渲染

9.路由拦截

(12)axios

1.get请求

2.post请求

3.axios全局引入(很少用,用4题的)

4.axios请求拦截封装

5.异步导致数据无法获取的处理方式


8.二级路由

20210723065024552.png

part1**.vue**

  1. <template>
  2. <h1>part1</h1>
  3. </template>
  4. <script>
  5. export default {
  6. name: "Home",
  7. };
  8. </script>
  9. <style scoped>
  10. </style>

part2**.vue**

  1. <template>
  2. <h1>part2</h1>
  3. </template>
  4. <script>
  5. export default {
  6. name: "Home",
  7. };
  8. </script>
  9. <style scoped>
  10. </style>

index.js 2021072306505848.png

  1. {
  2. path: '/list',
  3. name: 'list',
  4. component: () => import('../views/list/index.vue'),
  5. },

index**.vue**

  1. <template>
  2. <div>
  3. <h1>list list list</h1>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. name: "Home",
  9. };
  10. </script>
  11. <style scoped>
  12. </style>

Nav**.vue**

  1. {name: "列表展示",icon: "icon-licai",url: "/list",},

20210723065134642.png //写在这个位置

20210723065140775.png //正常

index**.js**

  1. {
  2. path: '/list',
  3. name: 'list',
  4. component: () => import('../views/list/index.vue'),
  5. --------------------------------------- 添加 -----------------------------------------------
  6. children: [{ //二级路由(子)
  7. //path:'testA', //写法是可行的(写法一)
  8. path: '/list/testA', //写法二
  9. name: 'testA',
  10. component: () => import('../views/list/part1.vue')
  11. },
  12. {
  13. path: 'testB',
  14. name: 'testB',
  15. component: () => import('../views/list/part2.vue')
  16. }]
  17. --------------------------------------------------------------------------------------------
  18. },

Nav**.vue**

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTA0MjU2OQ_size_16_color_FFFFFF_t_70

  1. --------------------------------------- 添加 -----------------------------------------------
  2. //二级路由
  3. <ul class="c_item">
  4. <li v-for="(s, j) in v.child" :key="j">
  5. <router-link :to="s.url">{
  6. {s.name}}</router-link>
  7. </li>
  8. </ul>
  9. --------------------------------------------------------------------------------------------
  10. ·
  11. ·
  12. ·
  13. {name: "列表展示",icon: "icon-licai",url: "/list",
  14. --------------------------------------- 添加 -----------------------------------------------
  15. child: [
  16. {name: "子列表A", url: "/list/testA"},
  17. {name: "子列表B", url: "/list/testB"},
  18. ],
  19. --------------------------------------------------------------------------------------------
  20. },

20210723065220332.png20210723065222127.png

2021072306522580.png//但是数据未展示出来

index**.vue**

  1. <template>
  2. <div>
  3. <h1>list list list</h1>
  4. --------------------------------------- 添加 -----------------------------------------------
  5. <router-view /> //二级路由出口
  6. --------------------------------------------------------------------------------------------
  7. </div>
  8. </template>
  9. <script>
  10. export default {
  11. name: "Home",
  12. };
  13. </script>
  14. <style scoped>
  15. </style>

20210723065249972.png//解决

20210723065257420.png20210723065258955.png

//两种情况

index**.js**

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTA0MjU2OQ_size_16_color_FFFFFF_t_70 1

//也可以传参,不过不方便传,说白了就是要传都传最好都传(比较复杂)

============================ 下面可以看下 ==============================

(1)路由配置

  1. const routes = [
  2. {path: '/home', component: Home},
  3. {
  4. path: '/news',
  5. component: News,
  6. children: [{ //二级路由(子)
  7. path: 'login', //news/login
  8. component: Login
  9. }, {
  10. path: 'regist/:name/:pwd', //news/regist/abc/123
  11. component: Regist
  12. }]
  13. },
  14. {path: '/', redirect: '/home'} //重定向
  15. ];

(2)二级路由渲染

  1. <div id="my">
  2. <router-link to="/home">Home</router-link>
  3. <router-link to="/news">News</router-link>
  4. <div>
  5. <router-view></router-view> //一级路由出口
  6. </div>
  7. </div>

定义组件

  1. var Home = {
  2. template: '#home'
  3. }
  4. var News = {
  5. template: '#news'
  6. }
  7. var Login = {
  8. template: '<h3>Login——获取参数:{
  9. {$route.query.name}}</h3>'
  10. }
  11. var Regist = {
  12. template: '<h3>Regist——参数:{
  13. {$route.params.name}}</h3>'
  14. }
  15. //对应的模块内容:
  16. <template id="home">
  17. <div>
  18. <h3>组件home</h3>
  19. </div>
  20. </template>
  21. <template id="news">
  22. <div>
  23. <h3>组件news</h3>
  24. <ul>
  25. <li>
  26. <router-link to="/news/login">用户登录</router-link>
  27. </li>
  28. <li>
  29. <router-link :to="'/news/regist/'+name+'/'+id">用户注册</router-link>
  30. </li>
  31. </ul>
  32. //二级路由出口
  33. <router-view></router-view>
  34. </div>
  35. </template>

9.路由拦截

定义:路由拦截就是路由在发生变化时需要进行的拦截处理,比如登录拦截、权限拦截等;

写法:

路由拦截 //在跳转之前执行

beforeEach 函数有三个参数:

to:router 即将进入的路由对象

from 当前导航即将离开的路由

next:Function 进行管道中的一个钩子,如果执行完了,则导航的状态就是confirmed(确认的)否则为false,终止导航

afterEach 函数不用传next() //函数

index.js 20210723065444505.png

  1. ·
  2. ·
  3. ·
  4. //最下面
  5. router.beforeEach(function (to, from, next) {
  6. console.log(12345);
  7. next() //进入到下一步
  8. })

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTA0MjU2OQ_size_16_color_FFFFFF_t_70 2

//**点击路由都会打印一次**

Home**.vue**

  1. <template>
  2. <div class="home">
  3. --------------------------------------- 添加 -----------------------------------------------
  4. <button @click.once="sign()">{
  5. { msg }}</button>
  6. --------------------------------------------------------------------------------------------
  7. <img alt="Vue logo" src="../assets/logo.png" />
  8. </div>
  9. </template>
  10. <script>
  11. import HelloWorld from "@/components/HelloWorld.vue";
  12. export default {
  13. name: "Home",
  14. data() {
  15. return {
  16. --------------------------------------- 添加 -----------------------------------------------
  17. msg: "签到",
  18. --------------------------------------------------------------------------------------------
  19. };
  20. },
  21. --------------------------------------- 添加 -----------------------------------------------
  22. methods: {
  23. sign() {
  24. this.msg = "已签到";
  25. sessionStorage.setItem("sign", true);
  26. },
  27. },
  28. --------------------------------------------------------------------------------------------
  29. components: {
  30. HelloWorld,
  31. },
  32. };
  33. </script>
  34. <style scoped>
  35. </style>

20210723065516347.png

20210723065518662.png//true

index.js 20210723065522671.png ​​​​​​​

  1. ·
  2. ·
  3. ·
  4. //最下面
  5. router.beforeEach(function (to, from, next) {
  6. console.log(12345);
  7. --------------------------------------- 添加 -----------------------------------------------
  8. if (!sessionStorage.getItem('sign')) { //如果值不存在
  9. if (to.path !== '/home') { //另外就是已经在首页了,不能传首页to.path(路由对象)
  10. alert('请签到!');
  11. next(); //进入到下一步
  12. }
  13. }
  14. --------------------------------------------------------------------------------------------
  15. next() //进入到下一步
  16. })

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTA0MjU2OQ_size_16_color_FFFFFF_t_70 3

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTA0MjU2OQ_size_16_color_FFFFFF_t_70 4

//点击除了首页外的,都会显示请签到

20210723065557560.png

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTA0MjU2OQ_size_16_color_FFFFFF_t_70 5//这个时候点击其他路由就不会提示请签到

20210723065608970.png//但是回到首页时,已签到变成了签到

Home**.vue**

  1. <template>
  2. <div class="home">
  3. <button @click.once="sign()">{
  4. { msg }}</button>
  5. <img alt="Vue logo" src="../assets/logo.png" />
  6. </div>
  7. </template>
  8. <script>
  9. import HelloWorld from "@/components/HelloWorld.vue";
  10. export default {
  11. name: "Home",
  12. data() {
  13. return {
  14. msg: "签到",
  15. };
  16. },
  17. --------------------------------------- 添加 -----------------------------------------------
  18. mounted() { //挂载后
  19. this.msg = !sessionStorage.getItem("sign") ? "签到" : "已签到";
  20. },
  21. --------------------------------------------------------------------------------------------
  22. methods: {
  23. sign() {
  24. this.msg = "已签到";
  25. sessionStorage.setItem("sign", true);
  26. },
  27. },
  28. components: {
  29. HelloWorld,
  30. },
  31. };
  32. </script>
  33. <style scoped>
  34. </style>

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTA0MjU2OQ_size_16_color_FFFFFF_t_70 6

//去掉

20210723065639230.png

20210723065641221.png//还是这样

//解决,再次回到首页时,是已签到

=====================================================================

  1. router.beforeEach(function (to, from, next) {
  2. next()
  3. })

主要是对进入页面的限制;比如判断有没有登录,没有就不能进入某些页面,只有登录了之后才有权限

查看页面

​​​​​​​

  1. router.beforeEach(function (to, from, next) {
  2. if (!localStorage.getItem("username")) {
  3. if (to.path !== '/login') {
  4. next('/login')
  5. }
  6. };
  7. next()
  8. })
  9. /*在跳转之后判断*/
  10. //会在每次路由切换成功进入激活阶段时被调用
  11. Vue.afterEach(function (to, form) {
  12. console.log('成功浏览到: ' + to.path)
  13. })

(12)axios

安装:

npm install —save axios

Nav**.vue**

  1. {
  2. name: "axios",
  3. icon: "icon-yonghu",
  4. url: "/axios",
  5. },

index**.js**

20210723065807732.png

  1. {
  2. path: '/axios',
  3. name: 'axios',
  4. meta: {
  5. keepAlive: true, //需要缓存
  6. title: 'axios'
  7. },
  8. component: () => import('../views/axios/part1.vue')
  9. },

part1**.vue**

2021072306582178.png

  1. <template>
  2. --------------------------------------- 添加 -----------------------------------------------
  3. <button @click="send()">click</button>
  4. --------------------------------------------------------------------------------------------
  5. </template>
  6. <script>
  7. --------------------------------------- 添加 -----------------------------------------------
  8. import axios from "axios";
  9. --------------------------------------------------------------------------------------------
  10. export default {
  11. name: "Home",
  12. data() {
  13. return {
  14. title: 1,
  15. };
  16. },
  17. methods: {
  18. --------------------------------------- 添加 -----------------------------------------------
  19. send(){
  20. axios({
  21. method: "get",
  22. url: "http://localhost:3333/get_category",
  23. }).then((response) => {
  24. console.log("请求成功:" + response);
  25. }).catch((error) => {
  26. console.log("请求失败:" + error);
  27. });
  28. },
  29. --------------------------------------------------------------------------------------------
  30. },
  31. };
  32. </script>
  33. <style scoped>
  34. </style>

part2**.vue**

  1. <template>
  2. <h1>part2 ----获取参数:{
  3. { $route.query.id }}</h1>
  4. </template>
  5. <script>
  6. export default {
  7. name: "Home",
  8. };
  9. </script>
  10. <style scoped>
  11. </style>

20210723065848428.png

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTA0MjU2OQ_size_16_color_FFFFFF_t_70 7

=====================================================================

页面引入及调用:

  1. axios({
  2. method: 'get',
  3. url: 'http://localhost:3000/map/get'
  4. }).then(response=>{
  5. console.log('请求成功:' + response);
  6. }).catch(error => {
  7. console.log('请求失败:' + error);
  8. });

1.get请求

传入参数

http://localhost:3333/get\_table/?id=1&name=jindu

  1. axios.get('http://localhost:3333/get_table/', {
  2. params: {
  3. name: 'jindu',
  4. id: 1
  5. }
  6. params: this.user
  7. })
  8. .then(resp => {
  9. console.log(resp);
  10. }).catch(err => {
  11. console.log(err);
  12. })

2.post请求

  1. axios({
  2. method: 'post',
  3. url: 'http://localhost:3000/map/add1',
  4. data: {}
  5. }).then(function (response) {
  6. console.log(response)
  7. }).catch(function (error) {
  8. console.log(error);
  9. })

简写:

  1. axios.post('http://localhost:3000/map/add1', {})
  2. .then(function (response) {
  3. console.log(response)
  4. }).catch(function (error) {
  5. console.log(error);
  6. })

​​​​​​​

3.axios全局引入(很少用,用4题的)

main**.js**

  1. import axios from 'axios'
  2. Vue.prototype.$http = axios; //axios创建到原型对象中,$http 是变量(下面axios可换)
  3. axios.defaults.baseURL = 'http://127.0.0.1:3333/'

part1**.vue**

20210723070034135.png

  1. <template>
  2. <button @click="send()">click</button>
  3. </template>
  4. <script>
  5. --------------------------------------- 去掉 -----------------------------------------------
  6. import axios from "axios";
  7. --------------------------------------------------------------------------------------------
  8. export default {
  9. name: "Home",
  10. data() {
  11. return {
  12. title: 1,
  13. };
  14. },
  15. methods: {
  16. send() {
  17. ----------------------------------- 换成 this.$http -----------------------------------------
  18. this.$http ({
  19. method: "get",
  20. ----------------------------- 去掉http://localhost:3333/ ---------------------------------
  21. url: " get_category",
  22. --------------------------------------------------------------------------------------------
  23. }).then((response) => {
  24. console.log("请求成功:" + response);
  25. }).catch((error) => {
  26. console.log("请求失败:" + error);
  27. });
  28. },
  29. },
  30. };
  31. </script>
  32. <style scoped>
  33. </style>

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTA0MjU2OQ_size_16_color_FFFFFF_t_70 8

//**一样**

=====================================================================

main**.js**

  1. import axios from 'axios'
  2. Vue.prototype.$http = axios;
  3. axios.defaults.baseURL = 'http://127.0.0.1:3333/'

组件中请求的方式为

  1. this.$http({
  2. method: 'get',
  3. url: 'map/get'
  4. }).then(response => {
  5. console.log('请求成功:' + response);
  6. }).catch(error => {
  7. console.log('请求失败:' + error);
  8. });

4.axios请求拦截封装

全局处理请求、响应拦截的处理,常见处理请求动画,错误码等

去掉3题所写的代码:

index**.js**

20210723070145604.png

  1. import axios from 'axios'
  2. axios.defaults.baseURL = `http://127.0.0.1:3333`;
  3. // 添加请求拦截
  4. // 在发送请求之前做些什么
  5. axios.interceptors.request.use((config) => {
  6. return config;
  7. })
  8. // 添加响应拦截
  9. axios.interceptors.response.use((response) => {
  10. // 对响应数据做点什么
  11. return response
  12. }, err => {
  13. // 对响应错误做点什么
  14. return Promise.reject(err);
  15. })
  16. export default axios

main**.js**

  1. --------------------------------------- 去掉 -----------------------------------------------
  2. import axios from 'axios'
  3. Vue.prototype.$http = axios; //axios创建到原型对象中,$http 是变量(下面axios可换)
  4. axios.defaults.baseURL = 'http://127.0.0.1:3333/'
  5. --------------------------------------------------------------------------------------------

part1**.vue**

20210723070216494.png

  1. <template>
  2. <button @click="send()">click</button>
  3. </template>
  4. <script>
  5. --------------------------------------- 添加 -----------------------------------------------
  6. import axios from "@/api/index";
  7. --------------------------------------------------------------------------------------------
  8. export default {
  9. name: "Home",
  10. data() {
  11. return {
  12. title: 1,
  13. };
  14. },
  15. methods: {
  16. send() {
  17. ------------------------------------ 换成axios ---------------------------------------------
  18. axios({
  19. --------------------------------------------------------------------------------------------
  20. method: "get",
  21. url: "get_category",
  22. }).then((response) => {
  23. console.log("请求成功:" + response);
  24. }).catch((error) => {
  25. console.log("请求失败:" + error);
  26. });
  27. },
  28. },
  29. };
  30. </script>
  31. <style scoped>
  32. </style>

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTA0MjU2OQ_size_16_color_FFFFFF_t_70 9

//**一样**

​​​​​

也可以:

main**.js**

  1. Vue.prototype.url= "http://127.0.0.1:3333/";

part1**.vue**

20210723070304185.png

  1. <template>
  2. <button @click="send()">click</button>
  3. </template>
  4. <script>
  5. import axios from "@/api/index";
  6. export default {
  7. name: "Home",
  8. data() {
  9. return {
  10. title: 1,
  11. };
  12. },
  13. methods: {
  14. send() {
  15. axios({
  16. method: "get",
  17. ------------------------------- 添加this.url + ------------------------------------------
  18. url: this.url + "get_category",
  19. --------------------------------------------------------------------------------------------
  20. }).then((response) => {
  21. console.log("请求成功:" + response);
  22. }).catch((error) => {
  23. console.log("请求失败:" + error);
  24. });
  25. },
  26. },
  27. };
  28. </script>
  29. <style scoped>
  30. </style>

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTA0MjU2OQ_size_16_color_FFFFFF_t_70 10

=====================================================================

  1. import axios from 'axios'
  2. axios.defaults.baseURL = `http://127.0.0.1:3333`;
  3. // 添加请求拦截器
  4. // 在发送请求之前做些什么
  5. axios.interceptors.request.use((config) => {
  6. return config;
  7. })
  8. // 添加响应拦截器
  9. axios.interceptors.response.use((response) => {
  10. // 对响应数据做点什么
  11. return response
  12. }, err => {
  13. // 对响应错误做点什么
  14. return Promise.reject(err);
  15. })
  16. export default axios

页面调用:

  1. import axios from '@/api/index' //引入方式
  2. axios({
  3. method: 'post',
  4. url: '/map/add1',
  5. data: {}
  6. }).then(function (response) {
  7. console.log(response)
  8. }).catch(function (error) {
  9. console.log(error);
  10. })

5.异步导致数据无法获取的处理方式

1**)添加flag标记**

  1. data(){
  2. return {
  3. flag: false, //状态变化
  4. items: [],
  5. }
  6. }
  7. <ul>
  8. <li v-for="(item,i) in items" :key="i" v-if="flag">{
  9. { item.name }} </li>
  10. </ul >
  11. mounted(){ //挂载后
  12. this.getData()
  13. },
  14. methods: {
  15. getData(){
  16. this.$http({
  17. method: 'get',
  18. url: 'http://localhost:3333/get_table'
  19. }).then(response => {
  20. if (response.data.code == '200') {
  21. this.items = response.data.result;
  22. this.flag = true; //请求到数据改变flag的值
  23. }
  24. }).catch(resp => {
  25. console.log('请求失败:' + resp);
  26. });
  27. }
  28. }

2)**监听数据变化**

  1. watch: { //监听值的变化
  2. items: function(newValue, oldValue) {
  3. this.items = newValue;
  4. },
  5. }

发表评论

表情:
评论列表 (有 0 条评论,372人围观)

还没有评论,来说两句吧...

相关阅读