本文介紹傳值方式:父傳子、子傳父
父子組件的關係可以總結爲 prop 向下傳遞,事件向上傳遞。父組件通過 prop 給子組件下發數據,子組件通過事件給父組件發送消息
父組件向子組件進行傳值
父組件:
<template>
<div>
父組件:
<input type="text" v-model="name">
<br>
<br>
<!-- 引入子組件 -->
<demo :inputName="name"></demo>
</div>
</template>
<script>
import demo from './demo'
export default {
name: "index",
components:{
demo
},
data(){
return{
name:''
}
}
}
</script>
<style scoped>
</style>
子組件:
<template>
<div>
子組件
<span>{{inputName}}</span>
</div>
</template>
<script>
export default {
name: "demo",
props:{
inputName:''
}
}
</script>
<style scoped>
</style>
子組件向父組件進行傳值
子組件
<template>
<div>
子組件:
<span>{{childValue}}</span>
<!-- 定義一個子組件傳值的方法 -->
<input type="button" value="點擊觸發" @click="childClick">
</div>
</template>
<script>
export default {
name: "demo",
data(){
return{
childValue: '我是子組件的數據'
}
},
methods:{
childClick(){
// childByValue是在父組件on監聽的方法
// 第二個參數this.childValue是需要傳的值
this.$emit('childByValue', this.childValue)
}
}
}
</script>
<style scoped>
</style>
父組件
<template>
<div>
父組件:
<span>{{name}}</span>
<br>
<br>
<!-- 引入子組件 定義一個on的方法監聽子組件的狀態-->
<demo @childByValue="childByValue"></demo>
</div>
</template>
<script>
import demo from './demo'
export default {
name: "index",
components:{
demo
},
data(){
return{
name:''
}
},
methods:{
childByValue: function (childValue) {
// childValue就是子組件傳過來的值
this.name = childValue
}
}
}
</script>
<style scoped>
</style>
以上是本章全部內容