1.父组件向子组件传值,子组件用props来接收父组件传过来的值
2…子组件用this.$emit向父组件传值
子组件:
<template>
<!-- 这是子组件 -->
<div class="child">
<p>
这是父组件传给子组件的东西:
<span class="childCom">{{parentData}}</span>
</p>
<button @click="tranVal()">点击我,我可以给父组件传值</button>
</div>
</template>
<script>
export default {
name: "helloworld",
props: ["parentData"],//随便起个变量名来接受父组件传过来的值
data() {
return {
childVal: "子向父传值",
};
},
methods: {
tranVal() {
this.$emit("transEven", this.childVal); //transEven是传递事件,利用$emit向父组件传值
},
},
};
</script>
父组件:
<template>
<!-- 这是父组件 -->
<div class="home">
<p>父组件目前的东西:<span class="parentCom">{{toChildData}}</span></p>
<HelloWorld @transEven="parentVal" :parentData="toChildData"></HelloWorld>
</div>
</template>
<script>
import HelloWorld from "@/components/HelloWorld.vue";
export default {
name: "Home",
components: {
HelloWorld,
},
data() {
return {
toChildData:"父向子传值"
};
},
methods: {
parentVal(e){
//通过子组件传来的值改变父组件的值
// console.log(e,1111)
this.toChildData=e
}
},
};
</script>
结果:
点击子组件向父组件传值: