How can you effectively transfer a function into a child component within Vue.js?

Within my project, I have a child component named goback.vue, whose sole purpose is to navigate back one step in the history. The reason for my inquiry is that I intend to utilize this component across multiple other components and would like the flexibility to modify its style and template from a single location in the future.

Below is the code snippet of the goback.vue component:

<template>
    <span @click="backOneStep">
       <svg type="submit" class="arrowleft" >
          <use href="../static/icons/iconsset.svg#arrowleft"></use>
       </svg>
    </span> 
</template>
<script>
export default {
    name: 'goback',
    data () {
        return {
        }
    },
    methods: {
        backOneStep(){
        window.history.go(-1)
        },
    } 
}     
<script>

In several of my parent components, I import the child component as shown below:

<template>
  <div class="building">
    <div id="title">
      <goback></goback> // utilizing the child component here
    </div>  
  </div>
</template>
<script>
import goback from './goback.vue';
export default {
  components: {
    goback
  },
  name: 'maincomponent',
  data () {
    return {  
      }
    }
  },
  methods: { 
     backOneStep(){ // do I need to repeat this here?
      window.history.go(-1) 
    },
  }
}
</script>

My first query revolves around whether I should duplicate the method in all parent components or if it can be defined solely in the child component. Secondly, I encounter an error message:

[Vue warn]: Property or method "backOneStep" is not defined on the instance but referenced during render. Ensure that this property is reactive by declaring it in the data option or initializing it for class-based components. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

found in

 <Goback> at src/components/goback.vue
   <Depts> at src/components/depts.vue
     <App> at src/App.vue
       <Root>

Please note that although I reviewed the provided link, I am still encountering issues.

Following the above error message, another error arises:

[Vue warn]: Invalid handler for event "click": got undefined

found in

 <Goback> at src/components/goback.vue
   <Depts> at src/components/depts.vue
     <App> at src/App.vue
       <Root>

I seek advice on how to resolve these errors. Could this be linked to props? While attempting to declare the "backOneStep" prop in the data section of goback.vue, I am unsure if I executed it correctly. What element am I overlooking in this scenario?

Answer №1

If you want the parent component to navigate back when clicking on a child component, you can achieve this by using a `$emit` event:

<template>
  <span @click="navigateBack">
    <svg type="submit" class="arrowleft" >
      <use href="../static/icons/iconsset.svg#arrowleft"></use>
    </svg>
  </span> 
</template>
<script>
  export default {
    name: 'navigateBack',
    methods: {
      navigateBack() {
        this.$emit('back')
      }
    } 
  }     
</script>

Then, in the parent component:

<template>
  <div class="building">
    <div id="title">
      <navigateBack @back="window.history.go(-1)"></navigateBack>
    </div>  
  </div>
</template>

Answer №2

This component structure worked perfectly for me, as I needed a way to easily customize the style of an element without scattering it throughout my code:

The child component:

<template>
    <span v-on:click="$emit('back')">
        <svg type="submit" class="arrowleft" >
        <use href="../static/icons/iconsset.svg#arrowleft"></use>
        </svg>
      </span> 
</template>
<script>
export default {
    name: 'goback',
    data () {
        return {

        }
    } 
}     
</script>
<style scoped>
     //  add your styles here
</style>

In the parent component:

<template>
  <div class="building">
    <div id="title">
      <goback @back="window.history.go(-1)"></goback>
    </div>  
  </div>
</template>
<script>
import goback from './goback.vue';    
export default {
  components: {
    goback
  },
  methods: {
    backOneStep(){
      window.history.go(-1)
    },
  }
}
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What causes a browser to redirect when trying to update the value of the alt field in a Wordpress media image?

Attempting to create a bookmarklet for the Wordpress image gallery manager that triggers the sidebar when an image is clicked. The sidebar contains fields for alt text (input), legend, and description (both textarea). <a href="javascript:var t=document ...

JS Issues with generating accurate dates in JS/JS Date perplexities

Creating a custom datepicker has been a challenging task for me. I'm facing difficulties in understanding how JS Date works and need some assistance to bridge this knowledge gap. The issue arises when I attempt to generate dates using a for loop, resu ...

Creating dynamic buttons and textboxes on a JSP page

<form:form action="approveAccount.html" method="GET"> <input type="submit" value="approvAll"/> <p>List of Pending Accounts for Approval</p> <c:forEach items="${accountIdList}" var="val"> <li>${val}</li> ...

Python code malfunctioning only under a post request execution

My task involves executing a post request to initiate a child process for running my discord_bot.py script with the inclusion of a variable. The script runs smoothly when executed directly from the terminal; however, encountering crashes at a specific stag ...

Issue with back button functionality when loading page with history.pushState in JavaScript

My current issue involves loading a page via ajax using history.pushState. The page loads successfully, but the back button does not work as expected. I have included my code below for reference: function processAjaxData(response, urlPath){ document.wr ...

How to add a new row to a Kendo grid with a unique custom styling

I am looking for a way to insert new data into a Kendo grid, but I want the added row to have a custom class so that I can style it with a different background color. How can I achieve this? I have searched through all the documentation but couldn't f ...

What is the best way to extract the value of a string before a comma in Javascript?

I have a challenge where I need to eliminate the city from a city, state combination. For example, if I have the string "Portland, OR", I want to extract only "Portland". Can someone help me with a Javascript solution or guide me on how to achieve this usi ...

Italian calendar conversion for the react-multi-date-picker library

I recently integrated the react-multi-date-picker into my project, utilizing the multiple mode feature. However, I encountered an issue when trying to display the Italian calendar based on the language setting. Despite using locale="it", the calendar was n ...

Is the support for getPageSource().contains still available?

Using Selenium along with Javascript, I am attempting to utilize the command if(driver.getPageSource().contains("Yes!")) In order to check for the presence of Yes! anywhere on the page. However, I am receiving an error indicating that the comman ...

A guide on using jQuery-Tabledit and Laravel to efficiently update table rows

In Laravel, it is necessary to include the row ID in the request URL to update it, for example: http://localhost/contacts/16 The challenge arises when using jQuery-Tabledit, which requires a fixed URL during initialization on page load. Hence, the query ...

PHP - Issue with submitting form data using $_POST from within a Div text container

Having some trouble with the submission of the "about_me_container" div in my form using $_POST. I know that divs are not typically used with $_POST, so I tried changing the div to input type="text" and textarea but it still won't work. I also attempt ...

What is the reason for HTML Entity not functioning in the input title for React?

Can someone explain why I am unable to use the HTML Entity &le; in the HTML input title attribute when using a JavaScript constant, but it works fine with a string? The HTML Entity &le; represents the ≤ symbol. To demonstrate this issue, please ...

Using jQuery in a React project to enhance Bootstrap functionality

Currently, I am working on a React.js project where instead of utilizing React-Bootstrap, I have decided to incorporate Bootstrap's CSS directly into my project. Now, I find myself in need of importing jQuery in order to fully utilize features such as ...

Exploring the intricacies of detecting changes on a signature pad within an Angular

Currently, I have integrated a signature_pad and an email input field in my web application. Both fields need to be filled out for the next step to become enabled (x-ng-disabled="!checkSignatureAndEmail()"). The email field has a ng-model, ensuring immedi ...

The getJSON function yields a null value

When using the jQuery getJSON function, I am getting a null response even though everything seems to be written correctly: $.getJSON("/site/ajax/autocomplete/key", function(data) { alert(data); //null alert(data.term); //null }); I am working wit ...

I'm looking to find the Angular version of "event.target.value" - can you help me out?

https://stackblitz.com/edit/angular-ivy-s2ujmr?file=src/app/pages/home/home.component.html I am currently working on getting the dropdown menu to function properly for filtering the flags displayed below it. My initial thought was to replicate the search ...

When a non-empty variable is assigned to the v-model, the checkbox will be checked automatically

Here is the code snippet for updating user-submitted data in a form: <div class="myLabel">Repeat on: </div> {{ data.repeatOn }} <div class="myInput"> <input type="checkbox" id="1" value="1" v-model="data.repeatOn" :checked="data.re ...

I am unable to retrieve data from my Firestore database using Geofirestore within an Express application

I implemented a query in Express to retrieve my data. Below is the code for my Express function: app.get('/locatii', (req, res) => { const geofirestore = new GeoFirestore(db); const geocollection = geofirestore.collection('locati ...

Ways to convert a function to asynchronous

My experience with building async functions is minimal, and the documentation has left me feeling even more confused. I am using vue.js as my framework and making calls to firebase in my methods. Aim The issue arises when deleting a document in firebase ...

Tips for arranging Intervals in sequence?

I've been developing a customized Pomodoro timer with user-defined work and rest times. In my Timer component, I have the following initial logic: useEffect(() => { start(3); start(timeData.workTime); start(timeData.restTime); }, []) c ...