组件注册
首先子组件不需要做任何操作正常写代码即可(默认导出,被暴露给外部)。当需要使用一个子组件,我们需要在父组件中导入它。
组件名格式
MyComponent
为名注册的组件,在模板中可以通过 <MyComponent>
或 <my-component>
引用
局部注册
vue3写法
在使用 <script setup>
的单文件(即vue3写法)组件中,导入的组件可以直接在模板中使用,无需注册
父组件:
<script setup>
import ButtonCounter from './ButtonCounter.vue'
</script>
<template>
<ButtonCounter />
</template>
vue2写法
没有使用 <script setup>
,则需要使用 components
选项来显式注册
import ComponentA from './ComponentA.js'
export default {
components: {
ComponentA//相当于ComponentA: ComponentA
},
setup() {
// ...
}
}
全局注册
-
使用 Vue 应用实例的
.component()
方法,让组件在当前 Vue 应用中全局可用
import { createApp } from 'vue'
const app = createApp({})
app.component(
// 注册的名字
'MyComponent',
// 组件的实现
{
/* ... */
}
)
-
使用单文件组件,你可以注册被导入的
.vue
文件
import MyComponent from './App.vue'
app.component('MyComponent', MyComponent)
组件通信
父传子
父组件使用自定义属性,然后子组件使用 props接收父组件传递过来的数据
1、父组件 :v-bind绑定参数
<children :age="18"></children>
2、子组件:
vue3写法
在使用 <script setup>
的单文件组件中,props 可以使用 defineProps()
宏来声明
-
数组写法
<script setup>
const props = defineProps(['foo'])
console.log(props.foo)
</script>
-
对象写法
// 使用 <script setup>
defineProps({
title: String,
likes: Number
})
vue2写法
在没有使用 <script setup>
的组件中,prop 可以使用 props 选项来声明
-
数组写法
export default {
props: ['foo'],
setup(props) {
// setup() 接收 props 作为第一个参数
console.log(props.foo)
}
}
-
对象写法
// 非 <script setup>
export default {
props: {
title: String,
likes: Number
}
}
子传父
子组件通过$emit绑定自定义事件给父组件监听,父组件用v-on监听事件并写好对应的回调,子组件触发执行后,父组件根据监听的回调进行对应的处理
1、子组件:使用$emit 触发事件
vue3写法
<template>
<div class="item" @click="handleGoodClick(item.id)"></div>
</template>
<script setup>
const emits = defineEmits(["toGoodDetail","addCart"]);
const handleGoodClick = (goodId) => {
emits("toGoodDetail", goodId);
};
</script>
vue2写法
-
对象语法
//1.数组语法
// emits: ['send'],
//2. 对象语法
//添加校验
emits: {
//如果校验失败会弹出警告
send: function (count) {
if (count <= 5) {
return true;
} else {
console.log(123, '校验失败');
return false;
}
},
},
//需要用methods(根据情况)监听
methods:{
checkCode(num){
//第一个参数是自定义的事件,注意这里的事件必须要与在父组件给子组件注册的事件保持一致(即这里的send和下面父组件的@send);后面的都为参数,可传多个参数,可不传参
this.$emit("send",num)
}
},
2、父组件:v-on(缩写为 @
) 接收子组件事件反馈
//send事件,执行addBtn函数(写在父组件里面)
<children @send="addBtn"></children>
addBtn(count) {
//count接收参数 =>就是上面的num
//3.当子组件中的按钮被点击这个函数会执行
this.counter += count;
},