组件的注册
<!DOCTYPE html><html lang="zh-CN"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>组件的注册</title> <script src="https://unpkg.com/vue@next"></script></head><body> <div id="app"> <!-- vue指令的本质是什么? 自定义属性 --> <!-- <p v-text="'Hello World'"></p> --> <!-- vue组件的本质是什么? 自定义标签 --> <!-- <hello-World></hello-World> --> <button-counter></button-counter> <button-counter></button-counter> </div> <template id="counter"> <button @click="count++" >点赞: {{count}}</button> </template> <script> // const app = Vue.createApp(); // 注册组件有两种方法 // 1. 全局组件: 注册在vue实例上 // app.component('button-counter',{ // template:'#counter', // data(){ // return{ // count:0, // }; // }, // }); // 2. 局部组件: 注册vue实例的选项中 const app = Vue.createApp({ components: { // 可以使用规范的驼峰命名法, 不过在html中要转为蛇形 buttonCounter: { template: '#counter', data() { return { count: 0, }; }, }, }, }); app.mount('#app'); // 全局: vue实例上 // 局部: vue选项上 </script></body></html>
向子组件传参
<!DOCTYPE html><html lang="zh-CN"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>向子组件传参</title> <script src="https://unpkg.com/vue@next"></script></head><body> <div id="app"> <!-- 使用自定义属性将父组件参数传入子组件中 --> <button-counter username="admin" email="105127367@qq.com"></button-counter> </div> <template id="counter"> <p>用户名: {{username}}</p> <p>邮箱: {{email}}</p> </template> <script> const app = Vue.createApp(); app.component('button-counter', { template:'#counter', props: ['username', 'email'], }); app.mount('#app'); </script></body></html>
向父组件传参: 监听子组件事件
<!DOCTYPE html><html lang="zh-CN"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>向父组件传参: 监听子组件事件</title> <script src="https://unpkg.com/vue@next"></script></head><body> <div id="app"> <button-counter @review-count="review"></button-counter> </div> <template id="counter"> <button @click="count++" >点赞: {{count}}</button> <!-- 发布订阅 --> <!-- $emit(自定义事件名称, 向父组件传递的参数(可选)) --> <!-- $emit('reviewCount', this.count) --> <button @click="$emit('reviewCount', this.count)">评价</button> </template> <script> const app = Vue.createApp({ methods:{ review(count){ console.log(count); if (count >= 10) alert('大家好'); }, }, }); app.component('button-counter', { template: '#counter', data() { return { count: 0, }; }, }); app.mount('#app'); // 1. 父->子: props: [数组] // 2. 子->父: // 2.1 子发布事件: $emit(自定义事件, 参数?) // 2.2 父订阅事件: @自定义事件(...args) </script></body></html>