Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AmaanS's avatar
Level 1

Accessing child method in parent without $ref

I am trying to call the child method in parent using $ref but as i used view-router the ref is not working . getting error

runtime-core.esm-bundler.js:265 Uncaught TypeError: Cannot read properties of undefined (reading 'populateForm')

createBooks.vue

<template>
 
  </template>
  
  <script>
  export default {
    props:{
      bookToEdit:{
        type : Object,
        default :null,
      }
    },
    data() {
      
      };
    },
    watch: {
    bookToEdit(newBook) {
      if (newBook) {
        this.populateForm(newBook);
      }
    }
  },
    methods: {
      async submitForm() {
        try {
          let formData = {
            title: this.title,
            author: this.author,
            category: this.category,
            rating: this.rating,
            description: this.description
          };
          this.errors = {};
          if (this.bookToEdit){
            await this.$emit('update-book',{index:this.bookToEdit.index,formData});
          }
          else{
            await this.$emit('form-submitted', formData);
          }
          this.$router.push('/');
          this.clearForm();
        } catch (error) {
          if (error.response && error.response.status === 422) {
            this.errors = error.response.data.errors;
          } else {
            console.error('An error occurred:', error);
          }
        }
      },
     
      populateForm(book) {
      this.title = book.title;
      this.author = book.author;
      this.category = book.category;
      this.rating = book.rating;
      this.description = book.description;
    },
      handleFormError(errors) {
        this.errors = errors;
      }
    }
  };
  </script>
  

  

App.vue

<template>
  <navbar/>
  <router-view
    :books="books"
    :book-to-edit="bookToEdit"
    @form-submitted="addBook"
    @update-book="updateBook"
    @delete-book="removeBook"
    @edit-book="editBook"
    @form-error="handleFormError"
    ></router-view>
</template>
<script>
export default{
     //methods and data
    ....
editBook(payload){
      this.bookToEdit = payload.book;
      this.bookToEdit.index = payload.index; // Set the index here
      this.$router.push(`/books/${payload.index}/edit`)
      this.$refs.createBooksComponent.populateForm(this.bookToEdit);
    },
</script>

how can i replace this ref and use populateform

0 likes
4 replies
MohamedTammam's avatar

There are solution to bind this to make it working. However, your approach is anti-pattern and will cause more issues than it solves.

I recommend using events or store actions to achieve same behavior with less headache.

1 like

Please or to participate in this conversation.