定義組件時,如果是需要參數傳遞則,將要傳遞的參數放在`props`中,`props`可以是一個數組也可以是一個字典,字典中可以定義是否是必須傳遞和參數的類型。如下:
porps:{
books:{
type: Array,
required: true,
default: '四大名著'
}
}
在傳參時,需要在參數前加":"以示是動態數據而非靜態數據。如下:
<book-template :books='books'></book-template>
單一根元素:
如果自定義的組件中,會出現很多html元素,那么根元素必須只能有一個,其余的元素必須包含在這個根元素中。
錯誤示例:
<h4>{{title}}</h4> <div>此標簽沒有包含在同一根元素下,而是和上面的標簽並列</div>
正確示例:
<div id="father"> <h4>{{title}}</h4> <div>此標簽包含在同一根元素下,都包含在id為father的div下</div> </div>
整體的測試代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <title>Vue中給自定義屬性添加屬性</title> </head> <body> <div id="app"> <book-template :books='books'></book-template> </div> <script> Vue.component("book-template", { props: ['books'], template: ` <table> <thead> <tr> <th>序號</th> <th>書名</th> <th>作者</th> </tr> </thead> <tbody> <tr v-for="book,index in books"> <td>{{index+1}}</td> <td>{{book.title}}</td> <td>{{book.author}}</td> </tr> </tbody> </table> ` }) new Vue({ el: '#app', data: { books: [{ title: '水滸傳', author: '施耐庵', }, { title: '三國演義', author: '羅貫中', } ] } }) </script> </body> </html>