1. 全局组件
2. 局部组件
3. 常规属性传值(props属性传值)
4. v-bind传值
4.1 属性取值
4.2 在构造器向组件传值(v-bind)
5. 父子组件调用
5.1 父组件
5.2 子组件
6. 组件注册
官方文档:https://cn.vuejs.org/v2/guide/components-registration.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>Vue入门之组件</title> 7 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> 8 </head> 9 10 <body> 11 <div id="app"> 12 <!-- 全局组件 --> 13 <div> 14 <button-counter></button-counter> 15 </div> 16 <!-- 局部组件 --> 17 <div> 18 <button-inner></button-inner> 19 </div> 20 <!-- 常规属性传值 --> 21 <div> 22 <button-props here="hello" from-here="world"></button-props> 23 </div> 24 <!-- v-bind传值 --> 25 <div> 26 <button-props v-bind:here="message" :from-here="message"></button-props> 27 </div> 28 <!-- 父子组件调用 --> 29 <div> 30 <parent></parent> 31 </div> 32 33 </div> 34 35 <script type="text/javascript"> 36 // 自定义全局组件 button-counter => html里面的<button-counter></button-counter> 37 Vue.component(‘button-counter‘, { 38 data: function () { 39 return { 40 count: 0 41 } 42 }, 43 template: ‘<button v-on:click="count++">全局组件显示: {{ count }}</button>‘ 44 }); 45 46 // 子组件 47 var city = { 48 template: `<div>Sichuan of China</div>` 49 } 50 51 // 父组件 52 var parent = { 53 template: 54 `<div> 55 <p> Panda from China!</p> 56 <city></city> 57 </div>`, 58 components: { 59 "city": city 60 } 61 } 62 63 // 实例化 64 new Vue({ 65 el: ‘#app‘, 66 data: { 67 message: ‘hello‘ 68 }, 69 // 定义局部组件 70 components: { 71 "button-inner": { 72 data: function () { 73 return { 74 inner: 0 75 } 76 }, 77 template: ‘<button v-on:click="inner++">局部组件显示: {{ inner }}</button>‘ 78 }, 79 // 取值 80 "button-props": { 81 template: `<div style="color:red;">参数1: {{ here }}:---参数2: {{fromHere}}</div>`, 82 props: [‘here‘, ‘fromHere‘] 83 }, 84 // 组件注册 85 "parent": parent 86 } 87 }); 88 </script> 89 </body> 90 91 </html>
原文地址:https://www.cnblogs.com/cisum/p/9618160.html
时间: 2024-10-11 05:51:47