VUE3父子组件传值 小范例代码

[复制链接]
查看: 642   回复: 0

246

主题

246

帖子

1369

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
1369
2023-5-27 15:44:31   显示全部楼层   阅读模式  
1.jpg



1.在Vue3中,子组件可以通过props接收父组件传递的值,也可以通过$emit方法向父组件发送事件。具体操作如下:

父组件传递值给子组件:
父组件中使用子组件时,可以在子组件标签上使用属性绑定的方式,将父组件中的数据传递给子组件:

<template>
  <div>
    <ChildComponent :msg="parentMsg" />
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue'

export default {
  name: 'ParentComponent',
  components: { ChildComponent },
  data() {
    return {
      parentMsg: 'Hello from parent!'
    }
  }
}
</script>

子组件中通过props接收父组件传递的值:
<template>
  <div>
    {{ msg }}
  </div>
</template>

<script>
export default {
  name: 'ChildComponent',
  props: {
    msg: String
  }
}
</script>
2.子组件向父组件发送事件:
子组件中通过$emit方法触发一个自定义事件,父组件通过在子组件标签上使用v-on绑定自定义事件的方式,监听子组件触发的事件并处理:
<template>
  <div>
    <button @click="sendMsg">发送消息到父组件</button>
  </div>
</template>

<script>
export default {
  name: 'ChildComponent',
  methods: {
    sendMsg() {
      this.$emit('send-msg', 'Hello from child!')
    }
  }
}
</script>
父组件中监听子组件触发的事件,并处理:
<template>
  <div>
    <ChildComponent @send-msg="handleMsg" />
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue'

export default {
  name: 'ParentComponent',
  components: { ChildComponent },
  methods: {
    handleMsg(msg) {
      console.log(msg)
    }
  }
}
</script>
<script setup>
import { reactive, toRefs, ref, onMounted, watch } from 'vue'
const prop = defineProps(
    {
        msg: String
    }
)
onMounted(() => {
})
</script>
<template>
    <div>
        <p class="titleP">{{ msg }}</p>
        <div class="line"></div>
        <div class="lineLong"></div>
    </div>

</template>

<style scoped lang='less'>
    .lineLong {
        width: 285px;
        height: 1px;
        //  background-color:green;
        background: linear-gradient(to right, rgb(255, 255, 255) 25%, rgba(255, 255, 255, 0.534) 45%, rgba(255, 255, 255, 0));
        position: absolute;
        top: 29px;
        left: 10px;
    }
.line {
    width: 5px;
    height: 3px;
    background-color: rgb(22, 214, 32);
    position: absolute;
    top: 28px;
    //left: 105px;
}

.gradient-bg {
    background: linear-gradient(to bottom, white 0%, white 25%, rgb(44, 133, 248) 38%, rgb(20, 100, 248) 100%);
    -webkit-background-clip: text;
    background-clip: text;
    /* 不带前缀的版本用于支持标准属性的浏览器 */
    -webkit-text-fill-color: transparent;
    /* 带前缀的版本用于较老的WebKit浏览器 */
    color: transparent;
    /* 标准属性,但某些浏览器可能还需要上面的-webkit-text-fill-color */
}

.titleP {
    .gradient-bg;
    color: white;
    width: 410px;
    height: 50px;
    text-align: left;
    // border: 1px rgb(0, 255, 76) solid;
    left: 22px;
    position: absolute;
    // top: 11px;
    letter-spacing: 9.5px;
    font-style: italic;
    transform: scaleY(1.01);
    font-size: 17PX;
    font-weight: 600;
}
</style>

回复

使用道具 举报

您需要登录后才可以回帖   登录 立即注册

高级模式

南通谢凡软件科技有限公司