未在vue js上调用“创建”方法

时间:2019-07-08 00:38:13

标签: javascript vue.js vue-component

我有我的主要组件App.vue,在其中我已经在方法的对象中声明了created方法。但是它从来没有被调用过。

<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>

我怎么知道它没有被调用?该方法中的控制台语句不会被打印。

1 个答案:

答案 0 :(得分:1)

创建是Vue生命周期的一部分,您应该从方法内部将其提取。

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]
  },
}

在他们的文档中查看this example