首先我們假設(shè),這里的登錄組件(register.vue)是App.vue組件的子組件,是通過(guò)路由進(jìn)入登錄組件的。
登錄組件中用戶點(diǎn)擊登錄后,后臺(tái)會(huì)傳過(guò)來(lái)一個(gè)用戶名,我的App.vue組件中需要拿到這個(gè)用戶名,并將上面的“登錄注冊(cè)”字樣變?yōu)椤坝脩裘薄?
為了保證用戶刷新后用戶名不會(huì)消失,這里我用到了sessionStorage
代碼如下:
register.vue中用戶點(diǎn)擊登錄觸發(fā)signIn方法
signIn(){ this.formData = $(".form").serialize(); var that = this; this.$http.get("/api/user", this.formData) .then(response => { that.userName = response.data.data.user.userName; that.userHead = response.data.data.userHead; that.$emit('userSignIn', that.userName); }) .catch(error => { console.log(error); }); }這里為了測(cè)試我直接mock的數(shù)據(jù),真實(shí)情況應(yīng)該是this.$http.post
這里的重點(diǎn)是那句
that.$emit('userSignIn', that.userName);向父組件(App.vue)傳值
App.vue代碼HTML
<keep-alive> <router-view @userSignIn="userSignIn"></router-view></keep-alive>
App.vue代碼JS
export default { data(){ return{ userName: sessionStorage.userName } }, methods:{ //子組件(register)將用戶名傳過(guò)來(lái) userSignIn(userName){ sessionStorage.userName = userName; this.userName = sessionStorage.userName; } }}這樣父組件就可以使用用戶名,保持了登錄狀態(tài),并且因?yàn)槭褂昧藄essionStorage,刷新頁(yè)面也可以保持。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持錯(cuò)新站長(zhǎng)站。
新聞熱點(diǎn)
疑難解答
圖片精選