向子组件传值

2020-12-29 10:54 更新

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

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

  1. // api-test.stml:
  2. <template>
  3. <text>{title}</text>
  4. </template>
  5. <script>
  6. export default {
  7. name:'api-test',
  8. props:{
  9. title: String
  10. }
  11. }
  12. </script>

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

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

  1. // app-index.stml:
  2. <template>
  3. <view>
  4. <api-test title="Hello App!"></api-test>
  5. </view>
  6. </template>
  7. <script>
  8. import './components/api-test.stml'
  9. export default {
  10. name: 'app-index'
  11. }
  12. </script>

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

  1. // app-index.stml:
  2. <template>
  3. <view>
  4. <api-test v-bind:title="msg"></api-test>
  5. </view>
  6. </template>
  7. <script>
  8. import './components/api-test.stml'
  9. export default {
  10. name: 'app-index',
  11. data() {
  12. return {
  13. msg: 'Hello App!'
  14. }
  15. }
  16. }
  17. </script>

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

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号