1.挂载点
2.创建VUE组件实例(根组件)
3.创建全局组件
4.声明子组件及孙组件
5.组件与挂载点绑定
<!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@3/dist/vue.global.js"></script></head><body><!-- 挂载点 --><div id="app"><!-- 组件挂载 --><greeting /></div><script>// 应用实例const app = Vue.createApp({// 根组件配置项});// 全局组件(父组件)// app.component(组件名称,{组件配置项})app.component('greeting', {// html模板template: `<h2>Hello, {{uname}}</h2><button @click='setLike'>点赞 + {{count}}</button><!-- 命名规则: 小驼 -> 肉串 --><my-award v-if='count >= 10' />`,// 数据data() {return {uname: '王老师',count: 0,};},// 方法methods: {setLike() {this.count++;},},// 声明子组件(复数属性)components: {// 奖励组件myAward: {template: `<p>实在太受欢迎了</p>`,data() {return {};},components: {// 声明子的子组件// userName: 小驼// last-user-name : 肉串},},},});// 根组件实例 (vue应用与挂载点绑定)const vm = app.mount('#app');</script></body></html>
props:用于接收父组件中传来的参数(用的是自定义属性)
<!DOCTYPE html><html lang="en"><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@3/dist/vue.global.js"></script></head><body><div id="app"></div><!-- 父组件的模板 --><template id="parent"><counter uname='admin' email='nx99@qq.com'></template><!-- 子组件模板:必须使用ID选择符 --><template id="child"><p>UserName:{{uname}}</p><p>UserEmail:{{email}}</p></template><script>const app = Vue.createApp({//父组件template: `#parent`,});app.component('counter', {//子组件// props:用于接收父组件中传来的参数(用的是自定义属性)props: ['uname', 'email'],template: `#child`,})const vm = app.mount('#app');</script></body></html>
- 父 -> 子:自定义属性
- 子 -> 父:自定义事件
<!DOCTYPE html><html lang="en"><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@3/dist/vue.global.js"></script></head><body><!--1. 父 -> 子:自定义属性2. 子 -> 父:自定义事件--><div id="app"><counter @review='review'></div><template id="counter"><button @click="count++">点赞 + {{count}}</button><button @click="review()">评论</button></template><script>const app = Vue.createApp({methods: {review(count) {console.log(count);if (count >= 10) {alert('可以下课了');};},},});app.component('counter', {template: `#counter`,data() {return {count: 5,}},methods: {review() {this.$emit('review', this.count);},},})const vm = app.mount('#app');</script></body></html>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号