0

我需要使用带有选项 API 的 Vue.js 3 访问子组件的方法。How to access to a child method from the parent in vue.js 中有一个答案,但它适用于 Vue.js 2 和 Vue.js 3,但带有 Composition API。

我仍然尝试了这个,都在父组件中:

<dropdown-list @update="updateChildComponents"></dropdown-list>
<child-component-1 ref="childComponent1Ref" :url="url"></child-component-1>
<child-component-2 ref="childComponent2Ref" :url="url"></child-component-2>

methods: {
  updateChildComponents() {
    this.$refs.childComponent1Ref.childComponentMethod();
    this.$refs.childComponent2Ref.childComponentMethod();
  }
}
 

这实际上成功地访问了该方法,但我认为这可能不是正确的方法。

其次,我在子组件中使用了一个道具,该道具在父组件中更新并在子组件的方法中使用,该方法仅在第二个事件之后更新。我想这两个可能是相关的。

子组件:

props: ['url'],
methods: {
  childComponentMethod() {
    console.log(this.url); // can access the value from the previous event 
  }
}

我很感激任何帮助。

4

1 回答 1

0

对于父母和孩子之间的交流,您应该使用道具传递价值。如果父级中的值发生变化,则必须添加监视。它称为 1 方式绑定,因为父级无法看到子组件中的更改。

父母 -> 孩子 = 使用道具。

子 -> 父 = 使用发射和事件。

<script>
import { reactive,watch, computed,onMounted } from "vue";


export default {
  components: { 
  },
  props: { metadata: String },
  emits: [""],
  setup(props) {
    onMounted(async () => {
    //first initilize 
      if (props.metadata) {
        state.metadataName = props.metadata;
      }
    });
    //track after the changes in the parent
    watch(
      () => props.metadata,
      async (metadata) => {
        if (metadata) {
          
        }
      }
    );
    return {
     
    };
  },
};
</script>
于 2022-02-09T10:52:41.887 回答