1.Vue组件本质
自定义属性,自定义标签
<!--
1. 全局组件: 注册在vue实例上
2. 局部组件: 注册vue实例的选项中
-->
<!-- <div class="app">
<button-counter></button-counter>
</div>
<script>
const app =Vue.createApp();
app.component('button-counter',{
template:'<button>asdf</button>'
});
app.mount('.app');
</script> -->
<div class="app">
<button-counter></button-counter>
</div>
<template id="counter">
<button @click="count++">点赞: {{count}}</button>
</template>
<script>
const app =Vue.createApp();
app.component('button-counter',{
template:'#counter',
data(){
return{
count:0
}
}
});
app.mount('.app');
</script>
2.向子组件传参
<div id="app">
<!-- 使用自定义属性将父组件参数传入子组件中 -->
<button-counter username="admin" email="498446472@qq.com"></button-counter>
</div>
<template id="counter">
<p>用户名: {{username}}</p>
<p>邮箱: {{email}}</p>
</template>
<script>
const app = Vue.createApp();
app.component('button-counter', {
// props: 用数组接收父组件传入的自定义属性做为载体的参数
props: ['username', 'email'],
template: '#counter',
});
app.mount('#app');
</script>
3.向父组件传参
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');