【问题标题】:Trouble accessing vue components data within another component在另一个组件中访问 Vue 组件数据时遇到问题
【发布时间】:2018-05-04 21:03:36
【问题描述】:

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

我尝试通过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 数据有什么想法吗?

【问题讨论】:

    标签: javascript vue.js vue-component


    【解决方案1】:

    您可以在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>
    

    Simple fiddle example here

    【讨论】:

      猜你喜欢
      • 2019-07-02
      • 2019-01-07
      • 2021-02-16
      • 2017-10-10
      • 2018-08-03
      • 2017-10-17
      • 2018-07-01
      • 1970-01-01
      • 2019-07-20
      相关资源
      最近更新 更多