繁体   English   中英

无法访问另一个组件中的vue组件数据

[英]Trouble accessing vue components data within another 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数据的任何想法?

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

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>

这里简单的小提琴例子

暂无
暂无

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

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