子模块代码:
<template>
<div>
<h1>{{firstname}}</h1>
<h1>{{lastname}}</h1>
<h1>{{fullname()}}</h1>
</div>
</template>
//firstname和lastname为介绍父模块传递数据的参数
//通过使用this.$emit 自定义事件chardststus 返回 数据'ok'
<script>
export default {
name: "vchard",
props:['firstname','lastname'],
data() {
return {
firstname: '',
lastname: ''
}
},
components: {},
methods:{
fullname() {
this.$emit('chardststus', 'ok');
return this.firstname + this.lastname;
}
},
}
通过props接受父模块传递2个参数firstname和lastname,简单相加计算,通过自定义函数 chardststus 返回计算状态’ok’
父模块代码如下:
<template>
<div>
<vchard @chardststus="getstatus" v-bind:firstname="students.firstname" v-bind:lastname="students.lastname"></vchard>
</div>
</template>
//chardststus 为子模块自定义事件
//getstatus 为处理子模块自定义事件的函数
//firstname和lastname为子模块接受父模块单向传递数值的参数
<script>
import vchard from "./vchard";
export default {
name: "vparent",
data() {
return {
flag: true,
students: {
firstname:'yu', lastname: 'timothy'
}
}
},
components: {vchard},
methods: {
getstatus: function (status) {
if (this.flag) {
this.$alert(status);
this.flag = false;
}
}
},
}
通过函数getstatus监听子模块自定义函数chardststus,通过v-bind指令向子模块props定义的参数里面动态传递数据
至此简单父子模块之间相互传递数据已经完成。