子传父的3种方式

1.Props传

通过Pros将父亲的methods方法传给子,子用 click来接收这个方法。

A(父)

复制代码
<template>
  <div>
    <B :cutPrice="cutPrice"></B>
  </div>
</template>
<script>
import B from "./B.vue";
export default {
  data() {
    return {};
  },
  activated() {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    cutPrice(name){
        console.log(name);
    }
  },
  components: {B},
};
</script>
<style>
</style>
复制代码

B(子)

复制代码
<template>
    <div>
        <button @click="cutPrice(1)"></button>
    </div>
</template>
<script>
export default {
    props:["cutPrice"],
   data() {
      return {
      }
   },
   activated() {
   },
 watch: {
},
created(){
},
mounted(){
},
methods:{
}


}
</script>
<style>
</style>
复制代码

2.官方$emit

A(父)  自定义一个事件,在子中去触发

复制代码
<template>
  <div>
    <B  @updatePrice="cutPrice"></B>
  </div>
</template>
<script>
import B from "./B.vue";
export default {
  data() {
    return {};
  },
  activated() {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    cutPrice(name) {
      console.log(name);
    },
  },
  components: { B },
};
</script>
<style>
</style>
复制代码

子(B)

复制代码
<template>
  <div>
    <button @click="xx">123</button>
  </div>
</template>
<script>
export default {
 
  data() {
    return {};
  },
  activated() {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    xx(){
        this.$emit("updatePrice",11)
    }
  },
};
</script>
<style>
</style>
复制代码

3.通过在子$parent调用父亲A中的属性

A(父亲)

复制代码
<template>
  <div>
    <B></B>
  </div>
</template>
<script>
import B from "./B.vue";
export default {
  data() {
    return {};
  },
  activated() {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    cutPrice(name) {
      console.log(name);
    },
  },
  components: { B },
};
</script>
<style>
</style>
复制代码

B(子)

复制代码
<template>
  <div>
    <button @click="xx">123</button>
  </div>
</template>
<script>
export default {
 
  data() {
    return {};
  },
  activated() {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    xx(){
        // this.$emit("updatePrice",11)
        // console.log(this.$parent);
        this.$parent.cutPrice(22)
    }
  },
};
</script>
<style>
</style>
复制代码

 

posted @   ajaXJson  阅读(2453)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示