全局组件&局部组件&嵌套组件

it2023-05-23  66

全局组件:component <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"> <my-button></my-button> </div> </body> </html> <script src="node_modules/vue/dist/vue.js"></script> <script> Vue.component('my-button',{ template:'<div>{{msg}}</div>', data(){ return { msg:'lly' } } }) let vm=new Vue({ el:"#app", data:{ } }) </script> 局部组件 组件的三步骤:1.定义组件 2.注册组件 3.使用组件 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"> <my-button></my-button> </div> </body> </html> <script src="node_modules/vue/dist/vue.js"></script> <script> //组件的三步骤:1.定义组件 2.注册组件 3.使用组件 let myButton={ template:'<div>{{msg}}</div>', data(){ return { msg:'lly' } } } let vm=new Vue({ el:"#app", data:{ }, components:{ myButton } }) </script> 局部组件的优化 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"> <my-button></my-button> <hello></hello> </div> <template id="button"> <div>{{msg}}</div> </template> <template id="hello"> <div> hello </div> </template> </body> </html> <script src="node_modules/vue/dist/vue.js"></script> <script> //组件的三步骤:1.定义组件 2.注册组件 3.使用组件 let myButton={ template:'#button', data(){ return { msg:'lly' } } } let hello={ template:'#hello' } let vm=new Vue({ el:"#app", data:{ }, components:{ myButton, hello } }) </script>

运行的结果:

组件的嵌套 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"> <my-button></my-button> </div> <template id="button"> <div> {{msg}} <hello></hello> </div> </template> <template id="hello"> <div> hello </div> </template> </body> </html> <script src="node_modules/vue/dist/vue.js"></script> <script> //组件的三步骤:1.定义组件 2.注册组件 3.使用组件 let hello={ template:'#hello' } let myButton={ template:'#button', data(){ return { msg:'lly' } }, components:{ hello } } let vm=new Vue({ el:"#app", data:{ }, components:{ myButton } }) </script>
最新回复(0)