todoList
結合之前 Vuejs 基礎與語法
•使用 v-model 雙向綁定 input 輸入內容與數據 data
•使用 @click 和 methods 關聯事件
•使用 v-for 進行數據循環展示
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>TodoList</title> <script src="./vue.js"></script></head><body> <div id="root"> <div> <input v-model="inputValue"/> <button @click="handleSubmit">提交</button> </div> <ul> <li v-for="(item,index) of list" :key="index"> {{item}} </li> </ul> </div> <script> new Vue({ el: "#root", data: { inputValue: '', list: [] }, methods: { handleSubmit: function(){ this.list.push(this.inputValue) this.inputValue = '' } } }) </script></body></html>JSbin 預覽
todoList 組件拆分
Vuejs 組件相關 詳細參考組件基礎
全局組件
注冊全局組件,并在 HTML 中通過模板調用組件
//注冊全局組件 Vue.component('todo-item',{ template: '<li>item</li>' }) <ul> <!-- <li v-for="(item,index) of list" :key="index"> {{item}} </li> --> <todo-item></todo-item> <!-- 通過模板使用組件 --> </ul>JSbin 預覽
局部組件
在注冊了局部組件之后,直接通過模板調用是不可以的,必須要在最外層的 Vue 的實例中添加 components: { }進行組件聲明。
//注冊局部組件 var TodoItem = { template: '<li>item</li>' } new Vue({ el: "#root", components: { //局部組件需要聲明的 components 'todo-item': TodoItem }, data: { inputValue: '', list: [] }, methods: { handleSubmit: function(){ this.list.push(this.inputValue) this.inputValue = '' } } })JSbin 預覽
即通過局部注冊的組件,需要在其他的 Vue 實例中使用該局部組件。必須使用 components 對該局部組件進行注冊。
上面的實例中,要在 Vue 實例中使用 TodoItem 這個局部組件,就通過 todo-item 這個標簽來使用。當在實例中 注冊好了以后,才可以在模板里面使用這個標簽。這樣就算正確的使用了局部組件。
外部傳遞參數
給 todo-item 標簽添加 :content 屬性,值為循環的每一項的內容 "item",
這樣就可以吧 content 傳遞給 todo-item 這個組件
<todo-item v-for="(item,index) of list" :key="index" :content="item"></todo-item>
但是直接將組件改成是不行的
Vue.component('todo-item',{ template: '<li>{{content}}</li>' })需要讓組件接收屬性,所以要在todo-item組件里面定義props屬性,其值為一個數組 'content' 。
新聞熱點
疑難解答
圖片精選