數據驅動和組件化是vue.js兩個最重要的特點。組件化是為了方便代碼復用,提高開發效率。常見的vue組件寫法有四種,各有特色,適用于不同的場景。
結構:
// 組件的注冊 Vue.component( 'componentName', { template: // 組件的html結構, data(){ return{ // 組件中的屬性 } }, method: { // 組件中的方法 } ...... // 組件其他的屬性和方法 }) // 組件的使用 new Vue({ el: '#app' }) 在script標簽內通過Vue.component()定義一個全局組件,并通過new Vue()實例將組件應用到html文件中id為app的標簽內。
特點:
<1>可以直接在html文件中的script標簽內直接定義與使用;
<2>通過該方法定義的組件是全局組件,在任何Vue實例下都可以使用,適合項目比較簡單的場景;
<3>每次定義組件時都要重新使用Vue.component(),且組件名不能相同;
實例:
Welcome組件
結構:
// 構造組件對象 const componentName = { template: // 組件的html結構, data(){ return{ // 組件中的屬性 } }, method: { // 組件中的方法 } ...... // 組件其他的屬性和方法 } // 組件的使用 new Vue({ el: '#app', components: { // 組件注冊、調用 componentName } }) 在script標簽中通過定義一個組件對象,并通過Vue實例中components屬性將該組件注冊調用。
特點:
<1>與全局方式定義的組件相似,都可以直接在html文件中的script標簽中直接書寫組件與使用;
<2>只有在注冊過的Vue實例中才能使用該組件;
實例:
Welcome組件
結構:
<template id="componnet"> // 組件的html結構 </template> // 全局組件的注冊與使用 Vue.component( 'componentName', { template: '#component', data(){ return{ // 組件中的屬性 } }, method: { // 組件中的方法 } ...... // 組件其他的屬性和方法 }) new Vue({ el: '#app' }) // 局部組件的注冊與使用 const componentName = { template: '#component', data(){ return{ // 組件中的屬性 } }, method: { // 組件中的方法 } ...... // 組件其他的屬性和方法 } new Vue({ el: '#app', components: { // 組件注冊、調用 componentName } }) 使用template標簽將組件中的html結構寫在body標簽內部,在script標簽內按照全局組件和局部組件的方式注冊與使用。不同之處在于組件中template屬性是通過id引用。
特點:
<1>js文件中不包含html結構內容,實現結構與邏輯分離;
實例:
Welcome組件
結構:
<template lang="html"> // 組件中的html結構 </template> <script> //組件的邏輯 export default { // 組件的屬性和方法 } </script> <style lang="css" scoped> // 組件的樣式 </style>
新聞熱點
疑難解答
圖片精選