【问题标题】:passing data from component to another component vue.js将数据从组件传递到另一个组件 vue.js
【发布时间】:2017-10-22 12:39:22
【问题描述】:

将用户名从 login.vue 组件传递到 navbar.vue 组件,但此代码未在导航栏中显示用户名。并给我这个错误 属性或方法“用户名”未在实例上定义,但在渲染期间被引用。确保在 data 选项中声明响应式数据属性。

发现于

登录.vue

<script>
 import axios from 'axios';
    export default {
    name: 'login',
    data() {
       return {
        email: '',
        password: '',
        logged : false,
        username : '',
        errorMsg : '',
     }
    },
   methods: {
     signIn: function () {
       axios.post('url', {
       email: this.email,
       password: this.password,
      },
   {
    headers: {

    }
  }
  )
  .then(response => {
    if(response.status == 200){
      setTimeout(function(){window.location.replace('url');
      }, 1500);
      this.logged = true;
      this.username = response.data.user.full_name;
      console.log(this.username);
    }
  })
  .catch(error => {
    this.errorMsg = '** Incorrect username or passrord **';
  });
}

navbar.vue 显示来自 login.vue 的全名

<script>
  import login from './Login'
  export default {
    name: 'NavBar',
    data() {
      return {
      username : username,
      }
    },
   components: {
    login
   },
 }
</script>

【问题讨论】:

    标签: javascript mvvm vuejs2


    【解决方案1】:

    Vue 事件总线可以在这种情况下为您提供帮助。 1. 在你的 event-bus.js 文件中创建一个事件总线,比如

    import Vue from 'vue';
    export const EventBus = new Vue();
    
    1. 在 login.vue 中登录成功时创建一个事件。喜欢

      import { EventBus } from './event-bus.js'
      
      then(response => {
      
          if(response.status == 200){
            setTimeout(function(){window.location.replace('url');
            }, 1500);
            this.logged = true;
            this.username = response.data.user.full_name;
            EventBus.$emit('login', this.username);
            console.log(this.username);
      
          } })
      
    2. 在你的 navbar.vue 中接收事件

      从 './event-bus.js' 导入 { EventBus }
      
      EventBus.$on('登录', user => {
      
        控制台日志(用户)
      });
      

    在 google 上搜索 Vue eventBus 有几个关于这个的教程。

    你可以使用 vuex 来制作认证系统。

    【讨论】:

    • 对不起,我不明白你的回答,你能说得更清楚吗:)
    猜你喜欢
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 2018-08-12
    • 1970-01-01
    • 2020-05-25
    • 2017-06-10
    相关资源
    最近更新 更多