当前位置: 代码迷 >> 综合 >> 学习笔记——Vue中父子组件传值
  详细解决方案

学习笔记——Vue中父子组件传值

热度:32   发布时间:2024-03-08 23:55:22.0

在vue中,使用组件时,我们可能会在一个页面级组件中调用其他功能组件,例如数量加减的组件,那么如何使父子组件之间进行通信哪?

父组件向子组件传参:

父组件向子组件传递数据或函数,子组件接收后调用,在下面的例子中子组件点击事件触发时,会调用父组件传过来的函数,从而改变父组件中的数据msgFather,进而改变子组件中的msgSon。

<!-- 子组件 -->
<template><div><span style="color: red;" v-text="msgSon" @click="changeMsgSon"></span></div>
</template><script>export default {name: 'HelloWorld',props: {msgSon: {  type: String, required: true },changeMsgSon: {  type: Function, required: true }}}
</script>
<!--  父组件 -->
<template><div>这是主页<!-- 使用子组件 --><HelloWorld :msgSon="msgFather"  :changeMsgSon="changeMsgFather"></HelloWorld></div>
</template><script type="text/ecmascript-6">import HelloWorld from '../../components/HelloWorld';export default {name: 'Home',data: function() {return {msgFather: '你好,世界!'};},components: {HelloWorld},methods: {changeMsgFather: function() {this.msgFather = '世界,你好!';}},};
</script>

子组件向父组件传参:

第一种方式:函数调用传参

父组件向子组件传递数据或函数,子组件接收后调用,在下面的例子中子组件点击事件触发时,会调用父组件传过来的函数并向该函数中传递一个参数,从而改变父组件中的数据msgFather,进而改变子组件中的msgSon。以下例子中代码相对于上一例子只改变了两处地方。

<!-- 子组件:接收后的函数加入了参数 -->
<span style="color: red;" v-text="msgSon" @click.self="changeMsgSon('久违了,世界!')"></span><!-- 父组件:传递的值用接收的形参来赋值 -->
changeMsgFather(msg) { this.msgFather = msg; }

第二种方式:emit发射事件传参

子组件向父组件发射一个事件,可以带参数,也可以不带参数。父组件监听这个事件,并作出相应的操作

<!-- 子组件 -->
<span style="color: red;" v-text="msgSon" @click.self="$emit('changeMsg', 'Hello')"></span>
props: { msgSon: {  type: String, required: true } }<!-- 父组件 -->
<HelloWorld :msgSon="msgFather"  @changeMsg="changeMsgFather"></HelloWorld>

第三种方式:v-model实现

模拟了vue中的v-model来实现父子组件之间的传参,与第一个实例不同之处如下:

<!-- 子组件 -->
<span style="color: red;" v-text="msgSon" @click.self="$emit('changeMsg', 'Hello')"></span>
props: { msgSon: String },
model: {prop: "msgSon",event: "changeMsg"
}<!-- 父组件 -->
<HelloWorld v-model="msgFather"></HelloWorld>

以上就是现在学习的实现父子组件之间传参的三种方法。

  相关解决方案