先实现一个案列 小明花钱 爸爸的钱随之减少
1:点击花钱按钮,爸爸的钱就减少100,数据定义在父组件之中,所以对money操作的函数就要放在父组件之中,所以父组件 Child中绑定一个@update:money =“money=$event"
@update是自定义事件名称,
:money是父组件向子组件传过来的money
“money=$event"就是父组件当中的值修改为子组件传过来的值
这时在子组件中触发这个自定义事件 (update:money) 然后写下点击之后真正剩下的钱数
(money-100)
父组件
<template>
<div>
小明的爸爸现在有{{money}}元
<h2>不使用sync修改符</h2>
<Child :money="money" @update:money="money=$event"/>
</div>
</template>
<script type="text/ecmascript-6">
import Child from './Child.vue'
export default {
name: 'SyncTest',
data() {
return {
money:10000
}
},
components: {
Child,
Child2
}
}
子组件
<template>
<div style="background: #ccc; height: 50px;">
<span>小明每次花100元</span>
<button @click="$emit('update:money',money - 100)">花钱</button>
爸爸还剩{{money}}元
</div>
</template>
<script type="text/ecmascript-6">
export default {
name: 'Child',
props:['money']
}
</script>
下面写有修饰符sync的---作用都是一样的
父组件的child改成
<Child2 :money.sync="money"/>
这样写完代表子组件会给父子件传递一个money的值,也会给当前这个child2绑定一个自定义事件就叫update:money(虽然他没写update)但是会自动给绑定一个update事件
子组件child2,与child是相同的
<template>
<div style="background: #ccc; height: 50px;">
<span>小明每次花100元</span>
<button @click="$emit('update:money',money - 100)">花钱</button>
爸爸还剩 {{money}} 元
</div>
</template>
<script type="text/ecmascript-6">
export default {
name: 'Child2',
props:['money']
}
</script>
相同效果
总结:
理解传值过程:子组件的money是props接收过来的,然后money-100这个新值我要通过触发父组件绑定的自定义事件($emit(update:money))发送给父组件。
:money.sync 有两个含义
1:给子组件传递props:money
2:给当前子组件绑定一个自定义事件 时间名 update 属性名(update:money)
还有一个父子组件通信-$attrs 和$Listeners
$attrs:可以获取所有父组件传过来的props数据(props没有接收)
$listeners:可以获取父亲传递的自定义事件
通过绑定这两个属性 我可以把父组件的按钮里面的属性事件全部显示自组件这个按钮身上并且显示出来。