vue實(shí)現(xiàn)用戶登錄切換
本文實(shí)例為大家分享了vue實(shí)現(xiàn)用戶登錄切換的具體代碼,供大家參考,具體內(nèi)容如下
切換有問題
代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <span v-if="isUser"> <label for="username">用戶賬號</label> <input type="text" id="username" placeholder="用戶賬號"> </span> <span v-else> <label for="email">用戶郵箱</label> <input type="text" id="email" placeholder="用戶郵箱"> </span> <button @click="isUser = !isUser">切換類型</button> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { isUser: true } }) </script> </body> </html>
效果展示
存在問題
- 如果我們在有輸入內(nèi)容的情況下,切換了類型,我們會發(fā)現(xiàn)文字依然顯示之前的輸入的內(nèi)容。
- 但是按道理講,我們應(yīng)該切換到另外一個(gè)input元素中了。
- 在另一個(gè)input元素中,我們并沒有輸入內(nèi)容。
為什么會出現(xiàn)這個(gè)問題呢?
這是因?yàn)閂ue在進(jìn)行DOM渲染時(shí),出于性能考慮,會盡可能的復(fù)用已經(jīng)存在的元素,而不是重新創(chuàng)建新的元素。
在上面的案例中,Vue內(nèi)部會發(fā)現(xiàn)原來的input元素不再使用,直接作為else中的input來使用了。
解決方案
- 給對應(yīng)的input添加key
- 保證key的不同
完美版登錄小案例
input里面添加不同的key
代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <span v-if="isUser"> <label for="username">用戶賬號</label> <input type="text" id="username" placeholder="用戶賬號" key="username"> </span> <span v-else> <label for="email">用戶郵箱</label> <input type="text" id="email" placeholder="用戶郵箱" key="email"> </span> <button @click="isUser = !isUser">切換類型</button> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { isUser: true } }) </script> </body> </html>
效果展示
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- vue實(shí)現(xiàn)用戶長時(shí)間不操作自動退出登錄功能的實(shí)現(xiàn)代碼
- vue 實(shí)現(xiàn)用戶登錄方式的切換功能
- django rest framework vue 實(shí)現(xiàn)用戶登錄詳解
- Vue項(xiàng)目使用localStorage+Vuex保存用戶登錄信息
- vue-router beforeEach跳轉(zhuǎn)路由驗(yàn)證用戶登錄狀態(tài)
- vue通過cookie獲取用戶登錄信息的思路詳解
- 使用vue-router beforEach實(shí)現(xiàn)判斷用戶登錄跳轉(zhuǎn)路由篩選功能
- vue路由跳轉(zhuǎn)時(shí)判斷用戶是否登錄功能的實(shí)現(xiàn)
- Vue中保存用戶登錄狀態(tài)實(shí)例代碼
- vue.js實(shí)現(xiàn)用戶評論、登錄、注冊、及修改信息功能
相關(guān)文章
vue 使用lodash實(shí)現(xiàn)對象數(shù)組深拷貝操作
這篇文章主要介紹了vue 使用lodash實(shí)現(xiàn)對象數(shù)組深拷貝操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09VUE3+vite項(xiàng)目中動態(tài)引入組件與異步組件的詳細(xì)實(shí)例
在做vue3項(xiàng)目中時(shí),每次使用都需要先進(jìn)行引入,下面這篇文章主要給大家介紹了關(guān)于VUE3+vite項(xiàng)目中動態(tài)引入組件與異步組件的相關(guān)資料,需要的朋友可以參考下2022-09-09