【问题标题】:trigger function in child.vue after clicking button in parent.vue单击 parent.vue 中的按钮后触发 child.vue 中的功能
【发布时间】:2021-12-08 07:21:24
【问题描述】:

我正在与BootstrapVue 合作。

我的 parent.vue 中有一个方法,我将一个值 (this.propsIndex) 传递给我的 child.vue

现在我想每次在 child.vue 的方法中单击它时都使用这个 value - 但是如何触发我的函数并使其工作?

非常感谢!

如果可能的话,我想避免使用watch

我的父母.vue

<template>
  <div v-for="(id, index) in inputs" :key="index">
    <b-button @click="deleteViaIndex(index)">Delete</b-button>
    <child :indexProps="indexProps" />
  </div>

  <div>
    <b-button @click="addInput()">Add Input</b-button>
  </div>
</template>

<script>
  methods: {
    deleteViaIndex(index) {
      this.propsIndex= index;
    },

    addInput() {
      this.inputs.push({})
    },
  },

  data() {
    return {
      inputs: [{}],
      propsIndex: '',
    }
  }
</script>

我的 child.vue(脚本)

props: ["propsIndex"],

methods: {
  deleteViaParentIndex() {
    //HERE I WANT TO USE IT EVERY TIME IT WILL BE CLICKED IN MY PARENT.VUE
    //BUT FOR NOW IT'S NOT DOING ANYTHING WHEN I CONSOLE.LOG(this.propsIndex)
  }
}

【问题讨论】:

    标签: javascript vue.js vuejs2 components


    【解决方案1】:

    看起来像是命名不匹配。在子组件中,您有一个 prop propsIndex,但在父模板中您传递的是 indexProps

    在传递道具时,你必须记住,道具名称总是在第一部分,你传递的值应该放在后面。 https://vuejs.org/v2/guide/components-props.html#Passing-Static-or-Dynamic-Props

    此外,由于 HTML 属性名称不区分大小写,因此您应该以这种方式传递道具:

    <child :props-index="indexProps" />
    

    【讨论】:

      【解决方案2】:

      除了 Marcin 提到的命名不匹配之外,您还可以使用模板中的 ref 从父组件访问子组件:

      &lt;child ref="childrenComponents" :props-index="propsIndex" /&gt;

      由于v-for 中有多个子组件,这使得$refs 中的childrenComponents 成为一个组件数组。要对所有这些调用 deleteViaParentIndex,您需要遍历它们:

      deleteViaIndex(index) {
          this.propsIndex = index;
          this.$refs.childrenComponents.forEach(child => child.deleteViaParentIndex());
      }
      

      您还可以进行一项优化。

      由于您使用propsIndex 仅传递子组件使用的索引,并且您已经将索引作为deleteViaIndex 中的参数,您可以在@ 期间将其作为参数简单地传递给子组件987654330@ 函数调用,从而完全不需要propsIndex 数据:

      parent.vue:

      deleteViaIndex(index) {
          this.$refs.childrenComponents.forEach(child => child.deleteViaParentIndex(index));
      }
      

      child.vue:

      deleteViaParentIndex(index) {
          // operations using index
      }
      

      【讨论】:

      • 嗨,感谢您尝试帮助我 - 但至少我收到以下错误 Property 'each' does not exist on type 'Vue | Element | (Vue | Element)[]'. Property 'each' does not exist on type 'Vue'
      • 我认为问题在于eachforEach,...只能通过数组工作..因此我认为我不能在这里使用它..
      • 也在我的控制台中得到这个:[Vue warn]: Error in v-on handler: "TypeError: this.$refs.childrenComponents.each is not a function"
      • @patrick96 你说得对,我把我的图书馆搞混了。 childrenComponents 应该是一个数组,因此您应该能够使用 forEach 而不是 each
      猜你喜欢
      • 2021-11-28
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 2018-09-30
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多