vue3 组件传值

2022-05-23  本文已影响0人  __鹿__

一、父传子接
通过 props接受,在vue3里props是响应式的


image.png

二、子传父接
通过emit,由于vue3中的setup的this指向是 undefined。所以使用setup的第二个参数(context)中的emit属性去传值。


image.png

原始页面


image.png

点击改变数据后的页面


image.png

附上完整代码:
home.vue (父组件)

<template>
  <div class="box">
    <div style="border: 1px solid red" class="style">
      父组件区域
      <div>
        <p>{{ name }}</p>
        <input type="text" name="" v-model="name" id="" />
      </div>
    </div>
    <div style="border: 1px solid green" class="style">
      子组件区域
      <InFo
        :name="name"
        :sex="about.sex"
        :height="about.height"
        
        @hello="showHelloMsg"
      ></InFo>
    </div>
  </div>
</template>
<script>
import { ref, reactive, onMounted, toRefs } from "vue";
import InFo from "../components/info.vue";
export default {
  components: {
    InFo,
  },
  setup(props, context) {
    console.log(props, context);
    let name = ref("小明");
    let about = reactive({
      sex: "男",
      height: 180,
    });
    function showHelloMsg(data) {
      name.value = "小红";
      about.sex = "女";
      about.height = 160;
      console.log("子组件传来的数据", data);
    }
    onMounted(() => {
      console.log("页面加载时");
    });
    return {
      name,
      about,
      showHelloMsg,
    };
  },
};
</script>
<style scoped>
.box{
    display: flex;
    justify-content: space-between;
}
.style {
  width: 49%;
  text-align: center;
  padding: 16px 0px;
}
</style>

info.vue (子组件)

<template>
  <div>
    <div>
      <p>姓名:{{ name }}</p>
      <p>性别:{{ sex }}</p>
      <p>身高:{{ height }}</p>
      <button @click="hello">改变数据</button>
    </div>
  </div>
</template>
<script>
import { ref, reactive, h, onMounted, toRefs } from "vue";
export default {
  props: {
    //父传子接
    name: String,
    sex: String,
    height: Number,
  },
  emits: ["hello"], // 要声明接收到了hello事件,否则会报警告
  setup(props, context) {
    let { name, sex, height } = toRefs(props);
    let { attrs, slots, emit } = context;

    console.log(name.value);
    console.log(sex.value);
    console.log(height.value);

    function hello() {
      //调用父组件的方法并传值
      emit("hello", 666);
      //context.emit("hello", 666);
    }
    onMounted(() => {
      console.log("页面加载时");
    });
    return {
      hello,
    };
  },
};
</script>

上一篇 下一篇

猜你喜欢

热点阅读