517 註冊元件語法糖,模板的分離寫法
阿新 • • 發佈:2020-08-20
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <cpn1></cpn1> <cpn2></cpn2> </div> <script src="../js/vue.js"></script> <script> // 1.全域性元件註冊的語法糖 // 1.建立元件構造器 // const cpn1 = Vue.extend() // 2.註冊元件 Vue.component('cpn1', { template: ` <div> <h2>我是標題1</h2> <p>我是內容, 哈哈哈哈</p> </div> ` }) // 2.註冊區域性元件的語法糖 const app = new Vue({ el: '#app', data: { message: '你好啊' }, components: { 'cpn2': { template: ` <div> <h2>我是標題2</h2> <p>我是內容, 呵呵呵</p> </div> ` } } }) </script> </body> </html>
模板的分離寫法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <cpn></cpn> <cpn></cpn> <cpn></cpn> </div> <!--1.script標籤, 注意:型別必須是text/x-template--> <!-- <script type="text/x-template" id="cpn">--> <!--<div>--> <!--<h2>我是標題</h2>--> <!--<p>我是內容,哈哈哈</p>--> <!-- </div>--> <!--</script> --> <!--2.template標籤--> <template id="cpn"> <div> <h2>我是標題</h2> <p>我是內容,呵呵呵</p> </div> </template> <script src="../js/vue.js"></script> <script> // 1.註冊一個全域性元件 Vue.component('cpn', { template: '#cpn' }) const app = new Vue({ el: '#app', data: { message: '你好啊' } }) </script> </body> </html>