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>
<script>
export default {
name: 'Login',
data() {
return {
loginForm: {
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
//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>

浙公网安备 33010602011771号