1 使用腳手架工具用 webpack 模板初始化項目,用 webstorm 打開項目。src 目錄下是要編寫的源文件。
main.js 文件 是主入口文件,
在es6語法中,:function(){}可以簡寫為(){}
在vue-cli中定義data時,不再是對象,而是以function函數的形式返回對象
template模板下只能有一個子節點,否則會報錯
我將 App.vue 改名為TodoList.vue 因此修改 main.js 文件,
import TodoList from './TodoList' ... components: { todoList:TodoList },
main.js 文件內容如下

// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import TodoList from './TodoList' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', components: { todoList:TodoList }, template: '<todoList></todoList>' })
2 組件的屬性內容現在寫到 export default{} 對象中
在 vue 文件中將模板放在 <template> 標簽下
將腳本內容放到 <script> 標簽下
TodoList 組件內容如下
<template> <div> <input v-model="inputValue"/> <button @click="addItem">提交</button> <ul> <todo-item v-for="(item, index) of todoList" :key="index" :content="item" :index="index" @deleteItem="deleteItem" > </todo-item> </ul> </div> </template> <script> import TodoItem from './components/TodoItem' export default { components: { 'todo-item':TodoItem }, data () { return { inputValue: '', todoList: [] } }, methods:{ addItem () { this.todoList.push(this.inputValue); this.inputValue= ''; }, deleteItem (index) { this.todoList.splice(index,1); } } } </script> <style> </style>
在該組件中引用了 TodoItem 組件。在本組件中需要引入該組件, 使用 components 屬性,引用一個對象。該對象的鍵是在該組件的名稱,值是引用的組件名稱。
對於 components
對象中的每個屬性來說,其屬性名就是自定義元素的名字,其屬性值就是這個組件的選項對象。
3 子組件寫法和上面一樣
TodoItem.vue 文件內容如下

<template> <li v-text="content" @click="deleteItem"></li> </template> <script> export default { props:['content','index'], methods: { deleteItem () { this.$emit('deleteItem',this.index); } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
4 父子組件之間傳遞消息的方式和之前的博文一致。參看
5 最后的效果如下