1

I'm using ionic with vue to develop an app. I made a custom button and want to include in another component. I'm trying to assign a function to the button but doesnt seem to work. The error i got is this:

[Vue warn]: Invalid prop: type check failed for prop "onClick". Expected Function, got String with value "addTodo".

First time using vue.Thanks in advance.

Button component

<template>
<ion-footer>
    <ion-button fill="outline" expand="block" color="primary" @click="onClick">
        <ion-ripple-effect></ion-ripple-effect>
        {{text}}
    </ion-button>
</ion-footer>
</template>
<script>
export default {
props: {
    onClick:Function,
    text:String,
}
}
</script>

Another Component

<template>
  <ion-row>
      <ion-col>
        <main-btn text="Add Activity" onClick="addTodo"></main-btn>
      </ion-col>
    </ion-row>
  </ion-grid> 
</template>

<script>
import axios from 'axios';

export default {
    data() {
       return {
         todos: []
          }
    },
    methods: {
      addTodo() {
    this.$router.push({path: '/todos/add'})
   }
  },
    created() {
       axios.get('http://localhost:3001/todos')
     .then(res => this.todos = res.data)
   }
}
 </script>
3
  • did you try onClick="addTodo()" or :onClick="addTodo()"? Commented Sep 11, 2019 at 15:15
  • @BoussadjraBrahim doesnt work Commented Sep 11, 2019 at 15:18
  • :onClick="addTodo"? Commented Sep 11, 2019 at 16:21

2 Answers 2

2

Just change it up, you don't need to pass the function as a prop.

In your button component:

@click="$emit('click')"

In your "Another Component"

<main-btn text="Add Activity" @click="addTodo"></main-btn>

Just bubble up the click event from the child component.

Sign up to request clarification or add additional context in comments.

Comments

0

Your going backwards against the way Vue is intended to work. You always want to pass Props Down which consist of data the child components need and emit events upwards to the parents to handle the necessary function calls.

Your child component "main-btn" should look more like below

<ion-button fill="outline" expand="block" color="primary" @click="$emit("onClick")">
    <ion-ripple-effect></ion-ripple-effect>
    {{text}}
</ion-button>

This will allow any parent components to look for the onClick Event emitted by the child component and react accordingly. In your case the parent component only needs to change slightly.

  <ion-col>
    <main-btn text="Add Activity" @onClick="addTodo"></main-btn>
  </ion-col>

The parent component is looking for an onClick event and reacts accordingly by calling its addTodo function

https://v2.vuejs.org/v2/guide/components.html#Listening-to-Child-Components-Events

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.