I've got my main component App.vue
in which I've declared the created
method in my method's object. But it's never being called.
<template>
<div id="app">
<Header />
<AddTodo v-on:add-todo="addTodo" />
<Todos v-bind:todos="todos" v-on:del-todo="deleteTodo"/>
</div>
</template>
<script>
import Todos from './components/Todos'
import Header from './components/layout/Header'
import AddTodo from './components/AddTodo'
import axios from 'axios'
export default {
name: 'app',
components: {
Header,
Todos,
AddTodo
},
data() {
return {
todos: [
]
}
},
methods: {
deleteTodo(id) {
this.todos = this.todos.filter(todo => todo.id !== id)
},
addTodo(newTodo) {
this.todos = [...this.todos, newTodo]
},
created() {
// eslint-disable-next-line no-console
console.log('here');
axios.get('https://jsonplaceholder.typicode.com/todos?_limit=10')
.then(res => this.todos = res.data)
// eslint-disable-next-line no-console
.catch(err => console.log(err));
}
}
}
</script>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
line-height: 1.4;
}
.btn {
display: inline-block;
border: none;
background: #555;
padding: 7px 20px;
cursor: pointer;
}
.btn:hover {
background: #666;
}
</style>
How do I know it's not being called? The console statements within the method are not being printed.
Methods are defined either inside the method property or in Single File components. Here's how: inside the method property: **new Vue({ methods: { ** // add your function associated to event. in Single File Components: < script > export default { methods: { // add the function associated to event.
The best way to force Vue to re-render a component is to set a :key on the component. When you need the component to be re-rendered, you just change the value of the key and Vue will re-render the component.
Created is part of the Vue life-cycle, you should extract it from inside of methods.
name: 'app',
components: {
Header,
Todos,
AddTodo
},
data() {
return {
todos: [
]
}
},
created() {
// eslint-disable-next-line no-console
console.log('here');
axios.get('https://jsonplaceholder.typicode.com/todos?_limit=10')
.then(res => this.todos = res.data)
// eslint-disable-next-line no-console
.catch(err => console.log(err));
},
methods: {
deleteTodo(id) {
this.todos = this.todos.filter(todo => todo.id !== id)
},
addTodo(newTodo) {
this.todos = [...this.todos, newTodo]
},
}
Check out this example in their docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With