<counterCom :num="10">
//01 接收参数并定义默认值
props: {
'num': {
type: Number,
default: 11
}
}
//02使用参数num
data()
return{counter:this.num}
}
<template>
<div>
<h1> hello worldh1>
<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>