//子组件
<template>
  <div class="hello">
    <span>{{ msg }}</span>
    <div></div>
    <span>{{ num }}</span>
    <button @click="add">+</button>
  </div>
</template>

<script>
import { ref, watch } from "vue";
export default {
  name: "HelloWorld",
  props: {
    msg: {
      type: String,
      default: () => "默认值",
    },
  },
  setup(props,context) {
    //     vue3.0           vue2.0
    // context.attrs === this.$attrs
    // context.slots === this.$slots
    // context.emit  === this.$emit
    const num = ref(0);
    const obj = ref("儿子调用父级方法成功!")
    watch(
      () => props.msg,
      (count, prevCount) => {
        console.log(count);
        console.log(prevCount);
      }
    );
    function add() {
    num.value += 1;
    context.emit("update:FatherTalk",obj.value);//调用父级方法参数
    }
    function talk(res){
      context.emit("update:FatherTalk",res);//调用父级方法参数
    }
    return {
      num,
      add,
      talk
    };
  },
};
</script>
<style scoped lang="less">
</style>



//父组件
<template>
  <div id="home">
    <div>{{ msg }}</div>
    <button @click="change">改变</button>
    <input type="checkbox" />
    <HelloWorld :msg = msg  ref="RefChilde"  @update:FatherTalk="FatherTalk"></HelloWorld>
  </div>
</template>

<script>
import {
  ref, //ref() 函数用来根据给定的值创建一个(响应式的数据对象),传入的为基本数据类型,例如字符串、数字、boolean 等,返回值是一个对象,这个对象上只包含一个 value 属性

} from "vue";
import HelloWorld from "@/components/HelloWorld.vue";
export default {
  name: "Home",
  components:{
  HelloWorld
  },
  setup() {
    const msg = ref("这是父组件信息哦!");
    const RefChilde = ref(null);
    function change(){
      msg.value = "这是父亲的信息哦!";
      RefChilde.value.talk("父级调用儿子方法成功!");//调用子组件的方法,子组件表签绑定 ref="RefChilde",并且返回RefChilde,不然会报错
    }
    function FatherTalk(res){
        msg.value = res;
    }
    return {
     msg,
     change,
     FatherTalk,
     RefChilde
     
    };
  },
};
</script>
Logo

前往低代码交流专区

更多推荐