全局数据设置provide/inject

//  src / App.vue

<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<script>
import { getToken } from './utils/auth'
export default {
  name: 'App',
  provide() {
    return {
      globalDb: this
    }
  },
  data() {
    return {
      db: ''
    }
  },
  mounted() {
    if (getToken()) {
      const db = JSON.parse(getToken()).db
      this.db = db
    }
    // console.log(this.db, ' this.globalDb')
  }
}
</script>

// 登录后更新数据

//  src / views / login / index.vue

<template>
  <div class="login-container">
 // ...

  </div>
</template>

<script>
export default {
  name: 'Login',
  inject: ['globalDb'],
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入用户名'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        db: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        db: [{ required: true, message: '请选择账套', trigger: 'change' }]
      },
      loading: false,

    }
  },
  mounted() {
    // ...
  },
  methods: {

    handleLogin() {
      this.$refs.loginForm.validate(async valid => {
        if (valid) {
          this.loading = true
          try {
            await this.getClearStorage()
            const res = await this.$store.dispatch('Login', this.loginForm)
            if (res.Error === 0) {
              this.$message({
                message: res.Message,
                type: 'success'
              })
              this.loading = false
              this.globalDb.db = this.loginForm.db // 登录成功后更新数据
              this.$router.push({ path: '/' })
            } else {
              this.$message({
                showClose: true,
                message: res.Message,
                type: 'error'
              })
            }

            // console.log(res, ' res')
          } catch (error) {
            this.$message({
              showClose: true,
              message: '用户名或者密码不正确!',
              type: 'error'
            })
            this.loading = false
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
 // ...
</style>

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页