繁体   English   中英

登录 vuejs 后重新渲染导航栏

[英]Re-render navigation bar after login on vuejs

我尝试使用 vue 创建客户端登录,我有主要组件,嵌套的是导航栏和呈现内容的组件在创建导航组件时,我检查用户是否已登录以显示访客按钮并隐藏受保护部分的按钮我的问题是在我的登录组件上提交登录后我不知道如何触发我的导航栏组件的重新重新化以显示正确的按钮

我不知道我是否应该在我的主组件上有一个全局变量,或者我是否应该找到一种方法将一个事件从子组件发送到父亲,然后从主组件发送另一个事件到导航栏,或者更多简单但我不知道

如果您需要更多信息,请告诉我提前谢谢

主要问题是如何在同一层次结构的组件之间建立通信,为了解决这个问题,我实现了 Vue.js 文档中描述的事件总线方法:

https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication

我只是创建了一个名为 EventBus 的新 Vue 实例

// EventBus.js
import Vue from 'vue'
export default new Vue()

然后我将它全局包含在我的主 Vue 实例中

// main.js
import EventBus from './EventBus'
import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

Vue.prototype.$bus = EventBus

/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    template: '<App/>',
    components: { App }
})

有了这个,我可以在我的组件上发出事件并在具有相同层次结构的其他组件上监听它们,如下所示:

// Login.Vue
import axios from 'axios'
export default {
     name: 'login',
     data () {
         let data = {
             form: {
                  email: '',
                  password: ''
             }
         }
         return data
     },
    methods: {
        login () {
            axios.post('http://rea.app/login', this.form)
            .then(response => {
                let responseData = response.data.data
                this.$localStorage.set('access_token', responseData.token)
                this.$bus.$emit('logged', 'User logged')
                this.$router.push('/')
            })
            .catch(error => {
                if (error.response) {
                    console.log(error.response.data)
                    console.log(error.response.status)
                    console.log(error.response.headers)
                }
            })
        }
    }
}

我可以在我的其他组件上侦听触发的事件,在 create 方法上设置侦听器,如下所示:

// NavBar.js
export default {
     template: '<Navigation/>',
     name: 'navigation',
     data () {
         return {
             isLogged: this.checkIfIsLogged()
         }
     },
     created () {
         this.$bus.$on('logged', () => {
             this.isLogged = this.checkIfIsLogged()
         })
     }
 }

希望这可以作为参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM