Passing Functions as props in vue js

Viewed 10751

I'm trying to pass editTodo as props function from parent app.vue to child components ... TodoItem.vue component there is a list Of Items and Time returns to main user input of newTodo and dateTime field. Actually, I'm a new learner of Vue js there is a little knowledge of pass props b/w the components communication.

      <template>
  <div id="app" class="container">
    <TodoInput :addTodo="addTodo"
    :updateTodo="updateTodo" 
    
    />

    <todo-item v-for="(todo, index) in todos" 
    :key=todo.id 
    :todo=todo 
    :index =index 
    :removeTodo="removeTodo"
    :editTodo="editTodo" /> 
    
  </div>

  
 
</template>



<script>
import TodoInput from "./components/TodoInput.vue";
import TodoItem from "./components/TodoItem.vue";
 
export default {
  name: "App",
  components: {
    TodoInput,
    TodoItem,
  
  },
  data() {
    return {
     
      editing:false,
      editItems:{},
      
      
      todos: [
        // {
        //   id: 1,
        //   title: "",
        //   date: new Date(),
        //   editing: false,
        //   completed: false,
        // },
        // {
        //   id: 1,
        //   title: "",
        //   date: new Date(),
        //   editing: false,
        //   completed: false,
        // },
      ],
    };
  },
 

  methods: {
     editTodo(index, newTodo, dateTime){
     , ' dateTime ', dateTime)
    //  this.editItems = {
    //    id,
    //    title,
    //    time,
    //  }
      this.todo = newTodo
      this.todo = dateTime
      this.selectedIndex = index
      this.editing = true
    },

TodoItem.vue component there is a list Of Items and Time returns to main user input of newTodo and dateTime field.***enter code here

  • `**

    --> {{todo.title}} {{todo.time}}
    </div>
          <div class="remove-item" @click="removeTodo(index)">
              &times; 
          </div>
           <div class="edit-item"  @click="eiditTodo(index)"
           >
              <i class="fas fa-edit" id="edit"></i>
           </div>
    

export default { name: 'todo-item', props:{ todo:{ type: Object, required: true, }, removeTodo:{ type:Function, required:true, }, index:{ type:Number, required: true, },

},
data(){
    return{
        'id': this.todo.id,
        'title': this.todo.newTodo,
        'time': this.todo.dateTime,
      }

methods: 
   
    getEdit(){
     
        this.$emit('editTodo', this.selectedIndex)
    }

**`

1 Answers

Instead of passing a function as a prop to the child component in order to run it, you should instead emit an event from the child component and execute the function in the parent component.

To emit an event from the child component

@click="$emit('edit-todo')"

And then in the parent component

<div @edit-todo="editTodo">
</div>

Alternatively, you could just define the editTodo function in theTodoItem component and call it directly.

Related