一拐辽、父組件向子組件傳值
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>
二蛇更、子組件向父組件傳值
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(){
// 第一個參數(shù)fromChildValue是父組件v-on的監(jiān)聽方法
this.$emit('fromChildValue',this.childValue)
}
}
}
</script>