本文介绍传值方式:父传子、子传父
父子组件的关系可以总结为 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>
以上是本章全部内容