1.定义和使用
定义子组件components中新建一个CounterCom.vue
定义template
<template>
<button>1</button>
</template>
App.vue
(1) 导入子组件
import CountCom from './components/CountCom.vue'
(2) 注册子组件
components:{CountCom}
(3) 使用子组件
两种写法均可,
<CounterCom></CountCom>
<counter-com></counter-com>
2.父传子(以上面数据举例)
首先需要定义向子组件传的参数
App.vue
例如传一个数字类型,一个字符串类型
<counter-com :num="10" str="abc"></counter-com>
如果传参是字符串不需要在变量名前加":"
CounterCom.vue
(1)接受参数并定义默认值
props:{
"num":{type:Number,default:1},
}
父传子的数组是只读的(做默认值,读取显示),不能进行修改
如果传递过来的参数为Array数组,Object对象 -引用类型
引用的默认值使用函数返回值 default(){return:[ ]}
(2)使用参数num
data(){
return{counter:this.num}
}
3.子传父
使用$emit
CounterCom.vue
<button @click="counter++;$emit('counterchange',counter)">
如果需要写在函数中,下面写法适用
this.$emit("counterchange", this.counter)
App.vue
<CounterCom @counterchange="n=$event"></CounterCom>
$event是子组件传递变量的代名词,可以赋值到父元素的data,方便对数据操作
$emit(事件名,事件值)向父元素发送一个值,事件名(counterchange)和事件值(counter)是自定义的
$emit固定写法,事件的值(counterchange事件的值,也是子组件$emit的第二个参数 )