无法访问其他组件中的vue组件数据

时间:2018-05-04 21:03:36

标签: javascript vue.js vue-component

我希望我在这里遗漏一些简单的东西,因为看起来应该有一个简单的解决方案。我试图通过从子组件更改父组件上的v模型来隐藏父组件上的微调器。

我尝试通过this.$parent.datathis.$refs访问父级。 $ parent和$ refs似乎存在于控制台中,但我无法访问我要查找的数据。

我还尝试使用this.$dispatch('message-name', 'message')向“父”组件发送消息,导致以下错误

  

_this2。$ dispatch不是函数

这是我的孩子组件

SessionModal.vue

<template>
  <v-layout row justify-center>
    <v-dialog v-model="modalOpen" persistent max-width="290">
      <v-card>
        <v-card-title class="headline">Session Expired</v-card-title>
        <v-card-text>Please login to continue</v-card-text>
        <v-card-text>
          <v-form>
            <v-text-field prepend-icon="person" name="login" label="Email" type="text" v-model="email" ></v-text-field>
            <v-text-field prepend-icon="lock" name="password" label="Password" id="password" type="password" v-model="password"></v-text-field>
          </v-form>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="green darken-1" flat @click.native="signIn">SIGN IN</v-btn>
          <v-btn color="green darken-1" flat @click.native="sendToLogin">SIGN OUT</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-layout>
</template>

<script>
  import axios from "axios";
  import * as decode from "jwt-decode";

  export default {
    data () {
      return {
        modalOpen: null,
        email: null,
        password: null
      }
    },

    mounted () {
      this.checkAuthStatus()

      setInterval(function () {
        this.checkAuthStatus();
      }.bind(this), 15000);
    },

    methods: {
      setHeaders: function () {
        let token = localStorage.token;
        return { headers: {'token': token} }
      },

      checkAuthStatus: function () {
        axios.get(`${process.env.API_URL}/auth_status`, this.setHeaders())
        .then((resp) => {
          console.log('resp', resp);
          this.modalOpen = false;
        })
        .catch((err) => {
          console.log('auth failed', err.message);
          this.modalOpen = true;
        })
      },

      sendToLogin: function () {
        this.modalOpen = false;

        delete localStorage.token
        this.$router.push('/sign_in')
      },

      closeModal: function () {
        this.modalOpen = false;
      },

      signIn: function () {
        axios.put(`${process.env.API_URL}/login`, {email: this.email, password: this.password})
          .then(resp => { // Success
            this.badPassword = false;
            this.modalOpen = false;

            // set local storage
            localStorage.token = resp.data.token;

            // what I want to do...
            this.$parent.data.loading = false;


          }, error => { // Failed
              console.log('there is an error', error);
              this.badPassword = true
          });
      }
    }
  }
</script>

这是父组件

Payment.vue

<template>
  <v-app>
    <spin-baby-spin v-if="loading"></spin-baby-spin>
    <v-content>
      <session-modal></session-modal>
      <v-container fluid v-if="loading == false">
        <v-layout row>
          <v-flex>
            <v-card>
<-- rest of template -->

    <script>
  import Spinner from './Spinner';
  import SessionModal from './SessionModal';
  import axios from 'axios';
  import numeral from 'numeral';
  import * as decode from 'jwt-decode';
  import {Decimal} from 'decimal.js';

  export default {
    data () {
      return {
        insuffienctFunds: false,
        user: null,
        fee: 0,
        disableSubmit: false,
        success: false,
        valid: false,
        loading: true,
        currencyRates: null,
        e6: 1,
        beneficiaries: [],
        payment: {
          amount: '',
          originCurrency: 0,
          beneficiaryCurrency: 1,
          beneficiary: {
            text: '',
            id: null
          }
        },
        e1: null
    },

    components: {
      'spin-baby-spin': Spinner,
      'session-modal': SessionModal
    },

    methods: {

      submit: function () {
        this.disableSubmit = true;
        if (this.getTotal() > this.balance) {
          this.insuffienctFunds = true;
          this.disableSubmit = false
          return
        }
        const transferPayload = this.formatTransferData();
        axios.post(`${process.env.API_URL}/transfers`, transferPayload, this.setHeaders())
          .then((resp) => {
            console.log(resp)
            this.success = true;
          })
          .catch((err) => {
            console.log(err)
          })
      },

      decodeToken () {
        return decode(localStorage.token);
      },

      setHeaders: function () {
        let token = localStorage.token;
        return { headers: {'token': token } }
      },

      getUser: function () {
        let userId = this.decodeToken().userId;
        return axios.get(`${process.env.API_URL}/users/${userId}`, this.setHeaders())
      },

      getUserBalance: function () {
        let userId = this.decodeToken().userId;
        return axios.get(`${process.env.API_URL}/users/${userId}/balance`, this.setHeaders())
      },
    },

    mounted () {
      this.loading = false;
    },

    created() {
      this.loading = false;
      this.getUser()
        .then(user => {
          this.user = user.data
        })
      this.getUserBalance()
        .then(userBalance => { this.balance = userBalance.data.balance })
    }
  }
</script>

我已删除了我认为不会对此问题做出贡献的代码,以便更快地阅读。

我看到的行为是一旦模式弹出页面,用户就会通过模态登录。然后模态消失,但是微调器组件不会隐藏。即使组件似乎经历了vue组件生命周期并且按照loading模型

之外的预期进行安装

有关如何从SessionModal.vue组件访问Payment.vue数据的任何想法?

1 个答案:

答案 0 :(得分:1)

您可以在$emit方法中使用signIn

signIn: function () {
  axios.put(`${process.env.API_URL}/login`, {email: this.email, password: this.password})
    .then(resp => { // Success
      //...
      // what I want to do...
      this.$emit('loaded')
    }
  }  
}

并在父级中捕获此内容:

<session-modal @loaded="loading = true"></session-modal>

Simple fiddle example here