子组件和父组件的传值
父组件:
<template>
<!-- html界面 必须有主DIV包裹 -->
<div>
<h1>我是父组件----子组件在下面</h1>
<v-son title="我是父组件" message="交给你一项任务"></v-son>
</div>
</template>
<script>
//导入子组件
import son from "./01-son.vue";
export default {
data() {
return {
msg: ""
};
},
components: {
"v-son": son
}
};
</script>
<style lang="less" scoped>
</style>
在 父组件中引用子组件 01-son.vue ,然后在父组件中注册一下 在v-son 子组件中 添加任意的 title message
子组件 :
<template>
<!-- html界面 必须有主DIV包裹 -->
<div>
<h1>{{msg}}</h1>
<h1>父组件传过来的值 title-{{title}} 与 message {{message}}</h1>
</div>
</template>
<script>
//导入子组件
// import son from "./01-son.vue";
export default {
props: ["title", "message"],
data() {
return {
msg: "我是子组件"
};
}
};
</script>
<style lang="less" scoped>
</style>
在 子组件中通过 props 来获取父组件中传过来的自定义属性title 和message的值并显示在子组件中。
子组件传值给父组件
<template>
<!-- html界面 必须有主DIV包裹 -->
<div>
<h1>{{msg}}</h1>
<h1>父组件传过来的值 title-{{title}} 与 message {{message}}</h1>
<button @click="sendMsgToParent">发送消息到父组件</button>
</div>
</template>
<script>
//导入子组件
// import son from "./01-son.vue";
export default {
props: ["title", "message"],
data() {
return {
msg: "我是子组件"
};
},
methods: {
sendMsgToParent() {
//使用$emit发送消息
this.$emit("getMsgFromSub", this.msg);
}
}
};
</script>
<style lang="less" scoped>
</style>
子组件发送给父组件必须通过事件来发送 this.$emit("getMsgFromSub", this.msg); getMsgFromSub 是事件的类型 这个随便定义 就是后面的跟父组件对应上就可以了
父组件
<template>
<!-- html界面 必须有主DIV包裹 -->
<div>
<h1>我是父组件----子组件在下面</h1>
<h2>我是子组件发送过来的消息{{msg}}</h2>
<v-son title="我是父组件" message="交给你一项任务" @getMsgFromSub="getMsg"></v-son>
</div>
</template>
<script>
//导入子组件
import son from "./01-son.vue";
export default {
data() {
return {
msg: ""
};
},
components: {
"v-son": son
},
methods: {
getMsg(msg) {
this.msg = msg;
}
}
};
</script>
<style lang="less" scoped>
</style>
在父组件中子组件的位置上 声明getMsgFromSub=方法
在方法内部就可以拿得到子组件传过来的值了。