1.组件注册
组件注册可以在vue的实例上进行全局注册,也可以在vue的选项中进行局部注册
组件注册方法如下:声明-注册-使用
<div class="app">
<!-- 使用组件 -->
<button-counter></button-counter>
<title-components></title-components>
<user-info-components></user-info-components>
</div>
<!-- 组件声明 -->
<template id="counter">
<button @click="count++">点赞:{{count}}</button>
</template>
<template id="userInfo">
<p>用户名: {{username}}</p>
<p>邮箱: {{email}}</p>
</template>
<script>
const app = Vue.createApp({
//局部注册
components: {
userInfoComponents: {
// 声明组件的id
template: "#userInfo",
data() {
return {
username: "张三",
email: "zhangsan@qq.com",
};
},
},
titleComponents: {
// 可以直接使用html标签声明
template: `<h3>{{title}}</h3>`,
data() {
return {
title: "用户信息",
};
},
},
},
});
//全局注册
app.component("buttonCounter", {
// 声明组件的id
template: "#counter",
data() {
return {
count: 0,
};
},
});
app.mount(".app");
</script>
2.组件之间的通讯
1.父->子:
props: [....]
2.子->父:
—2.1 子发布事件: $emit(自定义事件,参数?)
—2.2 父订阅事件: @自定义事件(…args)
<div id="app" class="demo">
<p>姓名: {{ name }}</p>
<p>邮箱: {{ email }}</p>
<!-- v-model 数据双向绑定 接收子组件传的参数 -->
<!-- 同时将name 和 email 的值传给子组件 -->
<!-- @alter-msg 自定义事件 alterMsg 定义函数来接收子组件传来参数 -->
<user-data v-model:name="name" v-model:email="email" @alter-msg="alterMsg"></user-data>
</div>
<!-- 组件声明 -->
<template id="userInfo">
<!--$emit('update:name', $event.target.value) 当input的值发生改变时向父组件传参 -->
<input type="text" :value="name" @input="$emit('update:name', $event.target.value)" />
<br />
<input type="text" :value="email" @input="$emit('update:email', $event.target.value)" />
<br />
<!-- 传参 -->
<!-- $emit('alterMsg',[this.name,this.email]) -->
<!-- alterMsg 自定义事件 -->
<!-- [this.name,this.email] 数组参数 -->
<button @click="$emit('alterMsg',[this.name,this.email])">查看用户信息</button>
</template>
<script>
const HelloVueApp = {
data() {
return {
name: "张三",
email: "zhangsan@qq.com",
};
},
components: {
userData: {
// 接收父组件userData传来的数据
props: ["name", "email"],
template: "#userInfo",
},
},
methods: {
//函数方法,接收父组件传的参数
alterMsg(arr) {
alert("姓名:" + arr[0] + " ,邮箱:" + arr[1]);
},
},
};
Vue.createApp(HelloVueApp).mount("#app");
</script>