[Vuejs]-VueJS – Using 'this' in a callback function

0👍

Here’s the solution to it, turns out you can use the ‘created’ life cycle hook, this is similar to react when binding in a constructor

<template>
  <div id="app">
    <Header/>
    <Tasks 
    :todos="todos"
    @onMarkAsDone="markAsDone"
    >
    </Tasks>
  </div>
</template>

<script>
import Header from './components/Header.vue';
import Tasks from './components/Tasks.vue';

export default {
  name: 'my-component',
  data() {
    return {
      name: 'Tasks',
      todos: [{
        id:0,
        text:'Complete this by lunch',
        isDone: false
      }]
    }
  },
  methods: {
    markAsDone(id) {
      console.log(this.todos); // can now access the correct 'this'
    }
  },
  created() {
    this.markAsDone = this.markAsDone.bind(this);
  },
  components: {
    Tasks,
    Header
  }
}
</script>

Sub component code

<template>
  <ul>
    <li 
      :class="{isDone:todo.isDone}"
      :key="todo.id" 
      v-for="todo in todos">
      <input type='checkbox' @change="markAsDone(todo.id)"/>
       {{todo.text}}
    </li>
  </ul>
</template>

<script>
export default {
  name: 'Tasks',
  props: ['todos'],
  methods: {
    markAsDone(id) {
      this.$emit('onMarkAsDone', id);
    } 
  }
}
</script>

0👍

You can return function in a markAsDone method, like this:

markAsDone() {
  return id => {
    console.log(this.todos);
  }
},

and then when passing method as a prop call it:

:onMarkAsDone="markAsDone()"

Then you can call the prop method inside your Child-Component.

That should give you requested functionality without using bind in created() hook.

Leave a comment