父子组件间传值
其一:父组件向子组件传值
第一种方式:用props父组件嵌套的子组件中。
使用v-bind:msg=‘xxxx’进行对象的绑定,子组件中通过定义props接收对应的msg对象。
父组件代码
<template>
<div>
<!-- 注意 :msg 后面是一个对象,值是字符串时,需要写冒号,如果省略:就是一个字符串 -->
<!-- <m-child msg="from Parent msg" ></m-child> -->
<m-child v-bind:msg="'from Parent msg'" ></m-child>
</div>
</template>
<script>
// 引入子组件
import MChild from './Child'
export default {
data () {
return {
msg: ''
}
},
components: {
MChild,
},
子组件代码
<template>
<div>
<h5>{{msg}}</h5>
</div>
</template>
<script>
export default {
// 要接受父组件传递的参数
props: {
msg: {
type: String,
default: ''
},
},
第二种方式:使用$children获取子组件和父组件对象
父组件代码:
this.msg2=this.$children[0].msg
第三种方式:使用$ref获取指定的子组件
父组件代码:
<m-child v-bind:msg="p2C" @showMsg='getChild' ref='child'></m-child>
this.c2P=this.$refs.child.msg33
其二:子组件向父组件传值
第一种方式:使用$emit传递事件给父组件,父组件监听该事件
子组件代码
<button @click="pushMsg()"></button>
methods: {
pushMsg() {
this.$emit("showMsg", "这是子组件===>父组件的值");
}
},
父组件代码
<m-child v-bind:msg="p2C" @showMsg='getChild' ref='child'></m-child>
methods: {
getChild(val) {
this.msg=val
},
}
第二种方式:使用$parent.获取父组件对象,然后再获取数据对象
子组件代码
mounted() {
this.msg22 = this.$parent.msg2;
}