vue 通过插槽组件之间数据传递

1.父向子传值

//--->Father.vue
<template>
  <div id="father">
    <p>黄色为父组件---data的值为:{{ data }}</p>
    <Son>
        <template #usname>
            <p>data的值为:{{data}}</p>//将父组件的data数据传入子组件的<slot>插槽
        </template>
    </Son>
  </div>
</template>

<script>
import Son from "./Son.vue";
export default {
  data() {
    return {
      data: "Father",
    };
  },
  components: {
    Son,
  },
};
</script>

<style scoped>
#father {
  width: 400px;
  height: 400px;
  background-color: yellow;
}
</style>

//--->son.vue
<template>
  <div id="son">
    <p>蓝色为子组件</p>
    <slot name="usname"></slot>
  </div>
</template>

<script>
export default {};
</script>

<style scoped>
#son {
  width: 200px;
  height: 200px;
  background-color: skyblue;
}
</style>

2.子向父传值

//--->Father.vue
<template>
  <div id="father">
    <p>黄色为父组件---data的值为:{{ data }}</p>
    <button @click="upp">1</button>//点击查看传过来的值
    <Son>
      <template #usname="obj">//通过v-slot指令接收son.vue传过来的值
        <p>data的值为:{{ data }}</p>
        <p>son_data的值为{{ obj.son }}</p>
        <button @click="son_data = obj.son">1</button
        >//通过点击按钮将传过来的值保存在Father组件的son_data数据中
      </template>
    </Son>
  </div>
</template>

<script>
import Son from "./Son.vue";
export default {
  data() {
    return {
      data: "Father",
      son_data: "",
    };
  },
  components: {
    Son,
  },
  methods: {
    upp() {
      console.log(this.son_data);
    },
  },
};
</script>

<style scoped>
#father {
  width: 400px;
  height: 400px;
  background-color: yellow;
}
</style>
//--->Son.vue
<template>
  <div id="son">
    <p>蓝色为子组件</p>
    <slot name="usname" :son='son_data'></slot>//添加自定义属性son将son_data数据传入父组件
  </div>
</template>

<script>
export default {
    data(){
        return{
            son_data:'Son'
        }
    }
};
</script>

<style scoped>
#son {
  width: 200px;
  height: 200px;
  background-color: skyblue;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值