uniapp父子组件传值三种方法

uniapp,父组件向子组件传值有三种方法,分别为props、slot,和ref

  1. props

这个应该是最简单最常用的方法,就是子组件写变量,然后把变量名字在js中进行props

<template>
        <view>
            <!-- 我是子组件 newzujian-->
            <view class="">
                {
    
    {value}}
            </view>
        </view>
    </template>
    <script>
        export default {
            props:['value'],
            methods:{
            }
        }
    </script>
<template>
        <view>
            <!-- 我是父组件 -->
            <newzujian value='789' >
            </newzujian>
        </view>
    </template>
    <script>
        export default {
            methods: {
                
                }
        }
    </script>
  1. slot

插值比较灵活,可以在任何需要写入的地方进行slot ,slot写入name标签后,在父组件进行插值#name

<template>
        <view>
            <!-- 我是子组件 newzujian-->
            <view class="">
                <slot name="value"></slot>
            </view>
        </view>
    </template>
    <script>
        export default {
            methods:{
            }
        }
    </script>
    <template>
        <view>
            <!-- 我是父组件 -->
            <newzujian  >
                <template #value>
                    789
                </template>
            </newzujian>
        </view>
    </template>
    <script>
        export default {
            methods: {
                
                }
        }
    </script>
  1. ref 函数控制

这个是父组件调用子组件的函数进行对子组件进行操作

    <template>
        <view>
            <!-- 我是子组件 newzujian-->
            <view class="">
                {
    
    {value}}
            </view>
        </view>
    </template>
    <script>
        export default {
            data(){
              return{
                  value:''
              }    
            },
            methods:{
                gaibian(){
                    this.value='789'
                }
            }
        }
    </script>
    <template>
        <view>
            <!-- 我是父组件 -->
            <newzujian ref="hanshu" >
                
            </newzujian>
            <button @click="dianji">click</button>
        </view>
    </template>
    <script>
        
        export default {
            onLoad() {
                
            },
            methods: {
                dianji(){
                    this.$refs.hanshu.gaibian()
                }
                }
        }
    </script>

猜你喜欢

转载自blog.csdn.net/zhtxilyj/article/details/129711112
今日推荐