vue 通過 Prop 向子元件傳遞資料的實現方法
阿新 • • 發佈:2020-10-30
這是一個通過 Prop 向子元件傳遞資料的小例子。
程式碼:
<!DOCTYPE html> <html lang="zh-cmn-Hans"> <head> <meta charset="UTF-8"> <title></title> <style> *{ margin: 0; padding: 0; text-decoration: none; } </style> </head> <body> <div id="app"> <!--資料的渲染--> <ul> <student-component v-for="item in students" :student="item"></student-component> </ul> </div> <script src="../vue.js"></script> <script> //子元件 //編寫學生元件 Vue.component('student-component',{ props:['student'],// props 可以是陣列或物件,用於接收來自父元件的資料。 template:`<li> <h3>學生的姓名:{{student.name}}</h3> <h3>學生的年齡:{{student.age}}</h3> <h3>學生的興趣:{{student.hobbies}}</h3> <hr/> <br/> </li>` }) //父元件 let app = new Vue({ el:'#app',data:{ //把這些資料傳給子元件 然後渲染到頁面上 students:[ { name:'丁七歲',age:19,hobbies:'吃飯 睡覺 打豆豆' },{ name:'丁七歲2',{ name:'丁七歲3',{ name:'丁七歲4',hobbies:'吃飯 睡覺 打豆豆' } ] } }) </script> </body> </html>
不再關心dom操作了 專注於資料的渲染。比如這個關注點 就是如何把 students這個陣列中的資訊渲染到頁面上給使用者看。
到此這篇關於vue 通過 Prop 向子元件傳遞資料的實現方法的文章就介紹到這了,更多相關vue Prop子元件傳遞資料內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!