Vue如何在页面加载时将url的参数赋值给组件

<template>
  <input v-model="loginForm.username" name="username" type="text" tabindex="1"  auto-complete="on" />
<input v-model="loginForm.password" :type="passwordType" name="password"  tabindex="2"/>
</template>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<script>
export default {
  name: 'Login',
  data() {
    return {
      loginForm: {<br>     username:'admin',//默认值
        password: '123456'
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined
    }
  },
  watch: {
    // 监测路由变化,只要变化了就调用获取路由参数方法将数据存储本组件
    $route: 'getQuery'
  },
  // mounted页面加载后执行,加载后调用了getQuery
  mounted() { this.getQuery() },
  methods: {
    getQuery() {
      var isAutoLogin = false
      if (this.$route.query.u !== undefined) {
        this.loginForm.username = this.$route.query.u //将获取到的值赋给loginForm对象的username属性
        isAutoLogin = true
      }
      if (this.$route.query.p !== undefined) {
        this.loginForm.password = this.$route.query.p
        isAutoLogin = true
      }
      this.redirect = this.$route.query && this.$route.query.redirect<br>    //url中带了账号密码则自动登陆
      if (isAutoLogin) { this.handleLogin() }
    },
    handleLogin() {
      //登陆
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm).then(() => {
            this.$router.push({ path: this.redirect || '/' })
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

  

posted @   兮去  阅读(241)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示