首页 > 解决方案 > 在 Vue 中跨组件传递数据

问题描述

我在我的 Django 项目的一个页面上加载了两个组件,一个用于从我的后端查询一些数据,另一个用于加载一些表单。

由于表单组件在页面上加载了四次(使用不同的参数),我无法从该组件查询数据,因为我会进行四次查询(每个组件一次),而我只需要做一次,所以我决定使用一个组件来进行查询,而表单组件应该只接收数据并将其与表单一起显示在页面上。

所以我有这个功能get_data.vue

..
methods: {
    fetchBalance() {
          fetch('MY-BACKEND')
            .then(response => response.json())
            .then(data => {

              var freeBalance = data['freeBalance']
              var totalBalance = data['totalBalance']

            })
        },

    }
..

然后我有form.vue

<template>
...
</template>

<script>

export default {

  props:{

    order:{
      type:String, 
      default:'amount'
    },

    side:{
      type:String, 
      default:'price'
     },


  },

  mounted() {

  },

  data() {

      return {
        name: '',
        description: '',
        output: ''
      };
  },

  methods: {
      formSubmit() {
          let currentObj = this;
          axios.post('MY-BACKEND', {        
              price: this.price,
              amount: this.amount,
          }

          .then(function (response) {
            currentObj.output = response.data;
          }

          .catch(function (error) {
              currentObj.output = error;
          });
      },

  }
}

</script>

不知何故,我需要访问变量freeBalancetotalBalanceget_data.vue. form.vue我怎样才能做到这一点?我正在考虑使用 Vuex,但我想看看是否有另一种方法可以在不使用 Vuex 的情况下做到这一点,因为这对于这项任务来说可能有点矫枉过正。

标签: vue.js

解决方案


将这些变量添加props到您的form.vue组件中(注意:我会将其重命名为其他名称,因为已经存在<form>DOM 对象)并将它们传入。

// MyForm.vue (renamed from form.vue to avoid conflict with the DOM object of the same name)

export default {

  props:{

    order:{
      type:String, 
      default:'amount'
    },

    side:{
      type:String, 
      default:'price'
     },

    freeBalance: {
      ...
    },

    totalBalance: {
      ...
    },
  },

// get_data.vue
<template>
  ...
  <my-form :free-balance="freeBalance" :total-balance="totalBalance" :order="..." :side="..."></my-form>
  ...
</template>

<script>
  ...
  data() {
    return {
      ...

      // define your variables here to make them available to the template
      freeBalance: null,
      totalBalance: null,
    }
  },
  methods: {
    fetchBalance() {
      fetch('MY-BACKEND')
        .then(response => response.json())
        .then(data => {
           this.freeBalance = data['freeBalance']
//         ^^^^^
           this.totalBalance = data['totalBalance']
//         ^^^^^

    }),
  },
}

在父组件的模板中使用道具名称时,请注意它们的 kebab-case。


推荐阅读