一、父组件传值给子组件
父组件调用子组件时绑定自定义属性,子组件通过props接收。
二、子组件传值给父组件
1、父组件调用子组件时自定义事件,子组件传值时触发该自定义事件。
2、父组件调用子组件时绑定自定义属性,属性是一个函数,子组件传值时直接调用该函数进行传值。
三、代码示例
代码中,App.vue是父组件,One.vue、Two.vue、Three.vue是子组件
它们之间的传值关系:
App.vue传值给One.vue
Two.vue传值给App.vue
Three.vue传值给App.vue
App.vue
<template>
<div id="app">
<input type="text" ref="in" />
<button @click="sendAction">按钮</button>
<hr/>
<!-- 父组件传值给子组件 -->
<!-- 父组件调用子组件时绑定自定义属性,子组件通过props接收。 -->
<one-com :val="value" />
<hr/>
<!-- 子组件传值给父组件 -->
<!-- 父组件调用子组件时自定义事件,子组件传值时触发该自定义事件。 -->
<p>接收到two的值为:{{twoData}}</p>
<two-com @send="handleSend" />
<hr/>
<!-- 子组件传值给父组件 -->
<!-- 父组件调用子组件时绑定自定义属性,属性是一个函数,
子组件传值时直接调用该函数进行传值。 -->
<p>接收到three的值为:{{threeData}}</p>
<three-com :sendAction="handleThreeData" />
</div>
</template>
<script>
import One from './components/One'
import Two from './components/Two'
import Three from './components/Three'
export default {
data(){
return {
value: 'test',
twoData: null,
threeData: null
}
},
methods: {
sendAction(){
this.value = this.$refs.in.value;
},
handleSend(val){
this.twoData = val;
},
handleThreeData(val){
this.threeData = val;
}
},
components: {
'one-com': One,
'two-com': Two,
'three-com': Three
}
}
</script>
<style>
</style>
One.vue
<template>
<div class="one">
<p>接收到的值为:{{ val }}</p>
</div>
</template>
<script>
export default {
props: ['val']
}
</script>
<style>
</style>
Two.vue
<template>
<div class="two">
<input type="text" ref="in" />
<button @click="btnAction">发送</button>
</div>
</template>
<script>
export default {
methods: {
btnAction(){
let val = this.$refs.in.value;
// 触发父组件绑定的自定义send事件
this.$emit('send', val);
}
}
}
</script>
<style>
</style>
Three.vue
<template>
<div class="three">
<input type="text" ref="in" />
<button @click="btnAction">发送</button>
</div>
</template>
<script>
export default {
props: {
sendAction: Function
},
methods: {
btnAction(){
let val = this.$refs.in.value;
// 直接调用sendAction函数进行传值
this.sendAction(val);
}
}
}
</script>
<style>
</style>