父传子
- 父组件向子组件传参,通过自定义属性的方式进行传参,在子组件中使用prop定义自定义的属性,然后在父组件中通过v-bind指令把需要传递的数据绑定在子组件上,那在子组件中props里面的自定义属性可以直接使用。
- 使用props
父传子的数组是只读的(做默认值,读取显示)
不能修改 - App.vue文件中
<counterCom :num="10">
- CounterCom.vue组件中
//01 接收参数并定义默认值
props: {
'num': {
type: Number,
default: 11
}
}
//02使用参数num
data()
return{counter:this.num}
}
- 父组件代码
<template>
<div>
<h1> hello world</h1>
<!-- 03 使用组件 -->
<CounterCom @counterchange='s=$event' :num='11'></CounterCom>
<counter-com @counterchange='m=$event' :num='m'></counter-com>
<counter-com @counterchange='n=$event'></counter-com>
<CounterCom></CounterCom>
<counter-com></counter-com>
<p>我有{{n}}元钱</p>
<p>我有{{m}}个男朋友</p>
<p>{{s}}</p>
</div>
</template>
<script>
// @counterchange 监听子组件触发的事件
// $event 固定写法 :事件的值
// 用 counterchange 事件去更新 n
// 01 导入 CounterCom 组件
import CounterCom from './components/CounterCom.vue'
export default {
// 02 注册 CounterCom 组件
components: {
CounterCom
},
data() {
return {
msg: 'vue-脚手架写大项目',
n: 11, //父组件定义值n
m: 1,
s: 2
}
}
}
// export 导出 default 默认 data 数据
// data(){} 是 data:function(){}的简写
</script>
<style scoped="scoped">
.green {
background-color: green;
color: #fff;
}
</style>
子传父
-
子组件向父组件传数据使用自定义事件, vue 组件提供了一个emit(‘自定义事件名’, 传递的数据) ),子组件传递数据时,触发响应的事件函数,就会自动触发通过$emit给父组件绑定的自定义事件,自定义事件接受一个参数,参数就是子组件传递过来的数据。
-
使用事件$emit
$emit(事件名,事件值) 发送一次事件,事件名(counterchange)和事件值(counter) 是自定义的 $ event 固定写法,事件的值(counterchange 事件的值,也是子组件$emit的第二个参数)
1.子组件 CounterCom.vue 中
<button @click="counter++; $emit('counterchange',counter)">
2.父组件 App.vue 中
<CounterCom @counterchange="n=$event">
- 子组件代码
<template>
<button @click="counter++;$emit('counterchange',counter)" class="active">
{{counter}}
</button>
</template>
<script>
// $emit('事件名',事件值 子组件主动触发一个事件,并传递一个值)
export default {
// 01 props 接收父 App.vue 传参 num
// props: ['num'],
// 定义传递过来的参数是数字列表,默认值是11
props: {
'num': {
type: Number,
default: 11
},
// Number 数字,String 字符串,Boolean布尔型-值类型
// Array 数组,Object 对象-引用类型
// 引用的默认值使用函数返回值 default(){return: []}
},
data() {
// 02 使用 num: 把传过来的 num 赋值给 counter
return {
counter: this.num
}
}
}
</script>
<style scoped>
/* 样式隔离:在scope中的样式只在本组件有用 */
.active {
color: orange;
font-weight: 600;
}
</style>