1

I need to access a child component's method using Vue.js 3 with Options API. There is an answer at How to access to a child method from the parent in vue.js, but it is for Vue.js 2 and Vue.js 3 but with Composition API.

I still tried this, all in the parent component:

<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>

and

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

This actually successfully accesses the method, but I think this may not be the right way.

Secondly, I use a prop in the child component that I update in the parent and use in the child component's method, which updates only after the second event. I think these two may be related.

Child component:

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

I appreciate any help.

Eylül
  • 139
  • 1
  • 3
  • 13
  • Why not to use on and emit? There are good examples in the question you mentioned – The scion Feb 09 '22 at 10:26
  • @Thescion I edited my answer. Using emit I can communicate from child to parent, I need the opposite. – Eylül Feb 09 '22 at 10:34
  • 1
    If you are changing the value in the parent, can't you see it rendering in the child? You try to add watch in the children? – The scion Feb 09 '22 at 10:39
  • 1
    There should basically be `url` watcher in child component that logs it. If your case differs consider updating the question. – Estus Flask Feb 09 '22 at 10:44

1 Answers1

0

For communication between the parent and the children you should trasfer the value with props. In case the value is changing in the parent you must add watch. It called 1 way binding because the parent cant see the changes in the child component.

Parent -> child = use props.

Child -> parent = use emits and on event.

<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>
The scion
  • 1,001
  • 9
  • 19