【问题标题】:Getting the value of a parent computed function, from a child component in VueJS从 VueJS 中的子组件获取父计算函数的值
【发布时间】:2021-05-26 16:01:29
【问题描述】:

我正在尝试将更改的计算方法的值传递给我的子组件,但收效甚微。我正在制作一个按钮组件,它有几种不同的保存状态 - 但我的按钮总是卡在一个上,并且不会与父级一起更新。

当我不尝试将此按钮用作组件并将其直接放入父级时,我的计算方法工作正常,所以问题是我如何传递数据。

父母

  computed: {
    isSaving() {
      return (
  this.$_.values(this.$store.getters["CommonSettings/saving"]).filter(
          status => status && status != "done"
        ).length > 0
      );
    }


 <SaveButton v-bind:saveState="isSaving"/>

孩子

<script>    
export default {
  name: "saveButton",
  props: ['saveState']
}
</script>
<template>
  <div class="settings--button-wrapper">
    <button v-if="!saveState">
      Save
    </button>
    <button v-if="saveState">
      Saving..
    </button>
  </div>
</template>

我是否在做任何明显错误的事情?

【问题讨论】:

    标签: javascript vue.js vue-component


    【解决方案1】:

    您应该使用 saveState 而不是 isSaving。

    【讨论】:

    • 谢谢,但我先尝试过,但没有解决我的问题。
    【解决方案2】:

    父母

    
    computed: {
        isSaving() {
          // add `this.`
          return (
              this.status && this.status != "done"
            )
          );
        }
    }
    
    <SaveButton v-bind:saveState="isSaving"/>
    

    孩子

    <script>    
    export default {
      name: "saveButton",
      props: ['saveState']
    }
    </script>
    <template>
      <div class="settings--button-wrapper">
        <!-- use `saveState` -->
        <button>
          {{ saveState ? 'Saving..' : 'Save' }}
        </button>
      </div>
    </template>
    

    【讨论】:

    • 对不起 - 正如我之前所说,当这个按钮不是一个组件时,计算方法可以正常工作(在同一个模板中使用它)。只有当我将此按钮拆分为一个单独的组件时,它才会中断 - 所以这并不能解决它。我认为问题是我的组件以初始状态呈现 - 然后它没有得到任何更新。
    • @s89_ &lt;button&gt; {{ saveState ? 'Saving..' : 'Save' }} &lt;/button&gt; 这能正常工作吗?
    • 很遗憾没有。就像我说的 - 我的按钮在它不是组件时可以正常工作。当父项中的保存状态发生更改时,数据未正确传递和更新。
    • @s89_ 这是正确答案。 I think the issue is my component is rendering with the initial state - and then it doesn't get any updates after that. - 完全正确!因为子组件中的isSaving 在创建子组件时(一次)被分配了saveState 属性的值。未来saveState 道具的更改(来自父母)对孩子的数据没有影响。这就是为什么你应该直接使用saveState prop
    • @MichalLevý - 是的 - 这是我最初尝试的。我又试了一次,但仍然不起作用,所以我仍然在这里遗漏了一些东西。直接使用 saveState 不会在孩子中更新。
    猜你喜欢
    • 2020-04-04
    • 2019-08-30
    • 2018-08-29
    • 2020-08-24
    • 2018-10-29
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 2017-03-17
    相关资源
    最近更新 更多