<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="./vue.js"></script> </head> <body> <div id="root"> <div> <input type="text" v-model="inputValue"> <button @click="handleSubmit">提交</button> </div> <ul> <todo-item></todo-item> </ul> </div> <script> //全局組件 // Vue.component('todo-item',{ // template:'<li>item</li>' // }) var TodoItem={ template:'<li>item</li>' } new Vue({ el:"#root", components:{ 'todo-item':TodoItem }, data:{ inputValue:'', list:[] }, methods:{ handleSubmit:function(){ this.list.push(this.inputValue); this.inputValue=''; } } }) </script> </body> </html>
3、組件傳值
父組件向子組件傳值是通過屬性的形式。
<div id="root"> <div> <input type="text" v-model="inputValue"> <button @click="handleSubmit">提交</button> </div> <ul> <todo-item v-for="(item ,index) of list" :key="index" :content="item" ></todo-item> </ul> </div> <script> Vue.component('todo-item',{ props: ['content'], //接收從外部傳遞進來的content屬性 template:'<li>{{content}}</li>' }) new Vue({ el:"#root", data:{ inputValue:'', list:[] }, methods:{ handleSubmit:function(){ this.list.push(this.inputValue); this.inputValue=''; } } }) </script>
三、組件與實例的關系
new Vue()實例
Vue.component是組件
每一個Vue組件又是一個Vue的實例。
任何一個vue項目都是由千千萬萬個vue實例組成的。
每個vue實例就是一個組件,每個組件也是vue的實例。
四、實現todolist的刪除功能
子組件通過發布訂閱模式通知父組件。
<div id="root"> <div> <input type="text" v-model="inputValue"> <button @click="handleSubmit">提交</button> </div> <ul> <todo-item v-for="(item ,index) of list" :key="index" :content="item" :index="index" @delete='handleDelete' ></todo-item> </ul> </div> <script> Vue.component('todo-item',{ props: ['content','index'], //接收從外部傳遞進來的content屬性 template:'<li @click="handleDeleteItem">{{content}}</li>', methods:{ handleDeleteItem:function(){ this.$emit('delete',this.index); } } }) new Vue({ el:"#root", data:{ inputValue:'', list:[] }, methods:{ handleSubmit:function(){ this.list.push(this.inputValue); this.inputValue=''; }, handleDelete:function(index){ this.list.splice(index,1); } } }) </script>
總結
以上所述是小編給大家介紹的Vue中父子組件通訊之todolist組件功能開發,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com