vue有 单项数据流特征:只允许父元素 向子元素中传递值,不允许子元素修改父元素的值
子父传参:必须是父元素主动传递一个函数给子元素,子元素通过这个函数来传递参数给父
父中定义一个事件(自定义,不与系统事件冲突即可),子中利用 $emit 来触发子元素中的自定义事件
例如:son中有几个button,父元素引入son,点击子组件的button后将内容显示在h3标签中:
父:
<template>
<div>
<h3>请说出你的选择:{{message}}</h3>
<son @sendMsg="getMsg" />
</div>
</template>
<script>
import Son from "../components/Son.vue";
export default {
data() {
return {
message: "",
};
},
methods: {
getMsg(msg) {
console.log("来自于子元素的信息:", msg);
this.message = msg
},
},
};
</script>
子:
<template>
<div class="box">
<button @click="choose('丫丫')">铭铭</button>
<button @click="choose('毛毛')">亮亮</button>
<button @click="choose('晶晶')">暗暗</button>
</div>
</template>
<script>
export default {
methods: {
choose(name) {
// 利用 $emit 来触发子元素中的自定义事件
// $emit(事件名, 事件参数)
this.$emit("sendMsg", name);
},
},
};
</script>