Vuejs学习笔记(二)-3.使用语法糖创建组件,节省代码
之前创建组件的代码略显繁琐,可以简化,使用到语法糖。
1.未使用语法糖创建全局组件
1 <!-- 2 @author:invoker 3 @project:project_lianxi 4 @file: 01-vue组件的基本使用.html 5 @contact:invoker2021@126.com 6 @descript: 7 @Date:2021/7/2 14:43 8 @version: html5 9 --> 10 11 <!DOCTYPE html> 12 <html lang="en"> 13 <head> 14 <meta charset="UTF-8"> 15 <title>01-vue组件的基本使用</title> 16 </head> 17 <body> 18 <div id="app"> 19 <h2>{{ message }}</h2> 20 <!-- 3.使用组件--> 21 <cpn1></cpn1> 22 </div> 23 24 <script src="../js/vue.js"></script> 25 <script> 26 27 // 1.创建组件构造器对象 28 const cpn = Vue.extend({ 29 template: ` 30 <div> 31 <h2>我是标题</h2> 32 <p>我是内容</p> 33 </div> 34 ` 35 }) 36 37 // 2.注册组件 38 Vue.component('cpn1', cpn) 39 const app = new Vue({ 40 el: '#app', 41 data: { 42 message: 'hello' 43 }, 44 }) 45 </script> 46 </body> 47 </html>
2.使用语法糖创建全局组件,组件的语法糖就是不使用Vue.extend构造一个组件,而是直接将内部template作为对象传入Vue.component组件注册中,省略了Vue.extend的代码。
<!-- @author:invoker @project:project_lianxi @file: 01-vue组件的基本使用.html @contact:invoker2021@126.com @descript: @Date:2021/7/2 14:43 @version: html5 --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>01-vue组件的基本使用</title> </head> <body> <div id="app"> <h2>{{ message }}</h2> <!-- 3.使用组件--> <cpn1></cpn1> </div> <script src="../js/vue.js"></script> <script> // 1.创建组件构造器对象 // const cpn1 = Vue.extend({ // template: ` // <div> // <h2>我是标题</h2> // <p>我是内容</p> // </div> // ` // }) // 2.注册组件 Vue.component('cpn1', { template: ` <div> <h2>我是标题</h2> <p>我是内容</p> </div> ` }) const app = new Vue({ el: '#app', data: { message: 'hello' }, }) </script> </body> </html>
3.使用语法糖创建局部组件
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>05 注册组件的语法糖</title> 6 </head> 7 <body> 8 9 <div id="app3"> 10 <h1>{{message}}</h1> 11 <cpn3></cpn3> 12 </div> 13 </body> 14 <script src="../js/vue.js"></script> 15 <script> 16 17 // case3.使用组件语法糖-局部组件 18 const app3 = new Vue({ 19 el: '#app3', 20 data:{ 21 message:'case3.使用组件语法糖-局部组件' 22 }, 23 components:{ 24 'cpn3':{ 25 template:` 26 <div> 27 <h1>组件3-局部组件</h1> 28 </div> 29 ` 30 } 31 } 32 33 }) 34 35 36 </script> 37 </html>
本文来自博客园,作者:kaer_invoker,转载请注明原文链接:https://www.cnblogs.com/invoker2021/p/14963640.html