一、父组件向子组件传值
![](https://img.haomeiwen.com/i14464062/63b566e872a48e7c.png)
1、父组件:
<template>
<div class="father">
<h1>父组件子组件相互传值</h1>
<h5>简单 / 易用 / 便捷</h5>
<h5>1:父组件向子组件传值</h5>
<div><span>父组件:</span><input type="text" v-model="inputValue"></div>
<child :fromFather="inputValue"></child>
</div>
</template>
<script>
//引入子组件
import Child from '../components/Child.vue'
export default {
name: 'Father',
components:{
'child':Child
},
data () {
return {
inputValue:''
}
}
}
</script>
2、子组件:
<template>
<div class="child">
<!-- 父组件向子组件传值-子组件接收值 -->
<div><span>子组件:{{fromFather}}</span></div>
</div>
</template>
<script>
export default {
name: 'Child',
props:{
fromFather: String,//在父组件中接收值
required: true
},
data () {
return {
}
}
}
</script>
二、子组件向父组件传值
![](https://img.haomeiwen.com/i14464062/a02f5d173a8bff5d.png)
1、父组件
<template>
<div class="father">
<h1>父组件子组件相互传值</h1>
<h5>简单 / 易用 / 便捷</h5>
<h5>2:子组件向父组件传值</h5>
<div><span>父组件:{{fromChild}}</span></div>
<child v-on:fromChildValue="fromChildValueAction"></child>
</div>
</template>
<script>
//引入子组件
import Child from '../components/Child.vue'
export default {
name: 'Father',
components:{
'child':Child
},
data () {
return {
fromChild:''
}
},
methods:{
// 子组件传过来的值
fromChildValueAction(text){
this.fromChild = text
}
}
}
</script>
2、子组件:
<template>
<div class="child">
<!-- 子组件向父组件传值 -->
<div><span>子组件:</span><button v-on:click="childValueAction">提交</button></div>
</div>
</template>
<script>
export default {
name: 'Child',
data () {
return {
childValue:'我是子组件中的值'
}
},
methods:{
childValueAction(){
// 第一个参数fromChildValue是父组件v-on的监听方法
this.$emit('fromChildValue',this.childValue)
}
}
}
</script>
网友评论