文章内容

2023/2/8 16:32:50,作 者: 黄兵

Vue3 父组件向子组件传值

父组件的内容如下:

<template>
<view class="content">
<view class="card-container">
<compress-result :download-video-url="downloadVideoUrl" v-if="complete" :compress-size="compressSize" :original-size="originalSize"></compress-result>
</view>
</view>
</template>

<script lang="ts">
import {defineComponent} from 'vue'
import CompressResult from "@/pages/index/compress-result.vue";

export default defineComponent({
components: {
'compress-result': CompressResult,
},
data() {
return {
disable: false,
loading: false,
uploading: true,
compress: false,
complete: false,
percent: 0,
compressSize: '',
originalSize: '',
downloadVideoUrl: '',
}
},

上面向子组件传递了 downloadVideoUrl, compressSize, originalSize 这些值。

子组件的内容如下:

<template>
<uni-card title="压缩结果">
<text class="uni-body">视频已压缩完成,以下是压缩后的详细信息:</text>
<text class="uni-body">视频原来大小:
<text class="strong">{{ originalSize }}MB</text>
</text>
<text class="uni-body">压缩后的视频大小:
<text class="strong">{{ compressSize }}MB</text>
</text>
<view class="progress-box" v-if="downloadLoading">
<progress :percent="percent" show-info stroke-width="3"/>
<text class="uni-body info">视频正在下载中,请稍等……</text>
</view>
<button class="download-button" type="default" @click="downloadVideo" :disabled="downloadDisable" :loading="downloadLoading">下载视频
</button>
</uni-card>
</template>

<script lang="ts">
import {defineComponent} from 'vue'
// 接收父组件传递过来的值
export default defineComponent({
setup(props) {
// 该入参包含了当前组件定义的所有 props
console.log(props)
},
name: "compress-result",
props: {
downloadVideoUrl: {
type: String,
default: "",
},
compressSize: {
type: String,
default: 0.0,
},
originalSize: {
type: String,
default: 0.0
}
},

上面使用的是 props 由父组件向子组件传递值。

另外官方文档推荐对 camelCase 风格(小驼峰)命名的 props ,在绑定时使用和 HTML attribute 一样的 kebab-case 风格(短横线),例如使用 user-name 代替 userName 传递。

  // 在这里需要添加一个入参
  setup(props) {
    // 该入参包含了当前组件定义的所有 props
    console.log(props)
  },

这里会显示所有传递过来的值,方便我们调试。

同时子组件对传递过来的值进行验证。


参考资料:

1、组件之间的通信


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - Vue3 父组件向子组件传值

分享到:

发表评论

评论列表