在vue-cli项目中动态修改系统名称

在vue-cli搭建的项目中有个系统配置页面,在系统配置页面中可以修改改系统的名称,要求修改完系统名后系统中相关显示系统名称的地方都要更改,包括登录页面、左侧导航栏、浏览器中的title

在这里将系统名称存在了localstorage和vuex中,存在Vuex中是因为Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。存在localstorage是方式页面刷新后vuex中的内容清空 所以综合起来 在两者内都存入

1.登录的时候 请求接口,获取接口名称,并将请求到的结果存放于localStorage和vuex中

//获取系统名称
getConfig() {
  configKey().then(response => {
    this.systemName = response.msg;
    localStorage.setItem('systemName', response.msg);
    this.$store.commit('app/SAVE_SYSTEM_NAME', response.msg);
    document.title = response.msg;
  })
},

这里顺便说一下  更改浏览器title直接用document.title来更改就可以 刚开始的时候 我一直在想怎么来更改title的值 通过监听还是定时请求接口 后来突然灵光一现 直接给document.title赋值即可

//在created中直接请求方法就可以 

created() {
  this.getConfig();
}

2.系统配置页面 可以系统名称 直接调用修改接口 修改完成后重新请求获取系统名称接口,在获取系统名称接口请求回来的数据会显示最新修改结果 并将请求回来的数据存放于localStorage和Vuex中

//修改系统名称
onSubmit() {
  this.$refs.form.validate(valid => {
    if (valid) {
      updateConfig({configValue: this.form.name}).then(response => {
        this.$modal.msgSuccess('修改成功');
        this.getConfig();
      })
    }
  })
}
//获取系统名称
getConfig() {
  configKey().then(response => {
    this.form.name = response.msg;
    localStorage.setItem('systemName', response.msg);
    this.$store.commit('app/SAVE_SYSTEM_NAME', response.msg);
    document.title = response.msg;
  })
},

3.Vuex中的代码

const state = {
  // 系统名称
  systemName:''
}
const mutations = {
  SAVE_SYSTEM_NAME:(state,name) =>{
    state.systemName = name;
  }
}
// 默认从vuex中获取数据 如果vuex中不存在(比如用户刷新了页面) 则从localStorage中获取
const getters = {
  getSystemName:state=>{
    return state.app.systemName || localStorage.getItem('systemName')
  }
}

4.在app.vue中修改 或者在index.html中修改 否则页面一刷新后title又恢复原样

// app.vue
export default {
  name: 'App',
  metaInfo() {
    return {
      title: this.$store.state.app.systemName || localStorage.getItem('systemName'),
      titleTemplate: title => {
        return title;
      }
    }
  }
}
//index.html
<script>
  document.title = localStorage.getItem('systemName')
</script>

猜你喜欢

转载自blog.csdn.net/workhard0905/article/details/122036109