阅读(2117) (0)

向子组件传值

2020-12-28 18:09:51 更新

向子组件传值采用 props 的方式,这里以一个示例来进行说明。

定义子组件,在 props 里面注册一个 title 属性:

// api-test.stml:


<template>
    <text>{title}</text>
</template>
<script>
    export default {
        name:'api-test',
        props:{
            title: String
        }
    }
</script>

这里定义的title属性类型为String,属性类型包括 String、Number、Boolean、Array、Object、Function等。

在其它页面使用子组件时传递静态值:

// app-index.stml:


<template>  
    <view>  
        <api-test title="Hello App!"></api-test> 
    </view>  
</template>
<script>
    import './components/api-test.stml'  

    
    export default {  
        name: 'app-index'
    }  
</script>

通过数据绑定传递动态值:

// app-index.stml:


<template>
    <view>
        <api-test v-bind:title="msg"></api-test>
    </view>
</template>
<script>
    import './components/api-test.stml'  

    
    export default {
        name: 'app-index',
        data() {
            return {
              msg: 'Hello App!'
          }
        }
    }
</script>

传递静态值时只能传递字符串类型数据,通过数据绑定的方式则可以传递任意类型的数据。