vue-antd-admin——实现全网站选项的切换并实现页面的刷新——技能提升

今天写后台管理系统时,遇到一个需求,是关于内外贸选项的切换。
就是在后台管理系统顶部,加一个内外贸下拉的选择进行切换,然后整个系统所有的接口调用时,传递不同的参数,进而获取到不同的数据。

效果图如下:
在这里插入图片描述
默认是内贸选项,当进行切换时,无论是在哪个页面,当前页面都要进行刷新,并将选项的参数传递到接口中。

下面详细介绍操作步骤:

1.AdminHeader.vue组件添加内外贸选项的切换

1.1 template中的相关代码如下:

 <a-dropdown class="lang header-item">
  <div>
    <a-icon type="pic-left" /> {
    
    {
    
     type == 1 ? '内贸' : '外贸' }}
  </div>
  <a-menu
    @click="(val) => setType(val.key)"
    :selected-keys="[type]"
    slot="overlay"
  >
    <a-menu-item v-for="type in dataTypeList" :key="type.value">{
    
    {
    
    
      type.label
    }}</a-menu-item>
  </a-menu>
</a-dropdown>

1.2 data中添加dataTypeList参数

data(){
    
    
	return{
    
    
		dataTypeList: [
	        {
    
     value: '1', label: '内贸' },
	        {
    
     value: '2', label: '外贸' },
	      ],
	}
}

1.3 从vuex中引入mapStatemapMutations

import {
    
     mapState, mapMutations } from 'vuex';

1.4 在computed中获取mapState中的type,从mapMutations中获取setType方法

computed: {
    
    
    ...mapState('setting', [
      'type',
    ]),
},
methods: {
    
    
	...mapMutations('setting', ['setType']),
}

2.store/modules/setting.js文件中添加type参数和setType方法

state:{
    
    
	type: '1',
},
mutations: {
    
    
	setType(state, type) {
    
    
      state.type = type;
    },
}

3.App.vue文件中添加以下的刷新代码

3.1 template中的代码如下:

<template>
  <a-config-provider :locale="locale" :get-popup-container="popContainer">
    <router-view v-if="isRouterAlive" />
  </a-config-provider>
</template>

3.2 data中的参数

data() {
    
    
  return {
    
    
    isRouterAlive: true,
  };
},

3.3 从vuex中引入mapStatemapMutations

import {
    
     mapState, mapMutations } from 'vuex';

3.4 在computed中获取mapState中的type,从mapMutations中获取setType方法

computed: {
    
    
    ...mapState('setting', [
      'type',
    ]),
},
methods: {
    
    
	...mapMutations('setting', ['setType']),
}

3.5 watch中监听type

watch: {
    
    
    type(newVal) {
    
    
      console.log('type改变了', newVal);
      this.reload();
    },
}

3.6 methods中添加刷新当前页面的方法

reload() {
    
    
  this.isRouterAlive = false;
  console.log('刷新当前页面了');
  this.$nextTick(() => {
    
    
    this.isRouterAlive = true;
  });
},

4.监听路由参数的变化,从而更改type的值

 watch: {
    
    
    $route() {
    
    
      console.log('route', this.$route.query);
      if(this.$route.query&&this.$route.query.dataType){
    
    
        this.setType(this.$route.query.dataType)//将路由中的参数设置到vuex中,调用接口的时候可以从vuex中获取
      }
      //this.setHtmlTitle(); 这个是设置标题啥的,此处无用
    },
 }

5.接口js文件中添加入参

import store from '../../store';//相对路径根据具体的来
console.log(store.state.setting.type);此时就可以拿到vuex中的参数了,然后调用接口的时候统一添加此参数即可。

完成!!!多多积累,多多收获!

猜你喜欢

转载自blog.csdn.net/yehaocheng520/article/details/129816215