uni-app属性绑定和事件绑定

前面操作的都是静态数据,本节开始模拟后端数据,uni-app 渲染后端数据的方式和 Vue 渲染后端数据的方式一模一样,代码如下。

M 层代码如下。

export default {
  data() {
    return {
      title: 'Hello'
    }
  },
  onLoad() {
  },
  methods: {
  }
}
html

视图层代码如下。

<template>
  <view class="content">
    {{ title }}
  </view>
</template>
html

代码解析如下。

视图层 uni-app 和 Vue 一样,使用插值表达式渲染 data 中的数据。

属性绑定

元素数据的绑定不能直接使用插值表达式,例如绑定元素的 title 属性、图片的 src 属性等,要使用 v-bind 进行属性绑定,代码如下。

M 层代码如下。

export default {
  data() {
    return {
      imgPath: '../../static/logo.png'
    }
  },
  onLoad() {
  },
  methods: {
  }
}
html

视图层代码如下。

<view class="content">
    <image :src="imgPath" mode="widthFix"></image>
</view>
html

代码解析如下。

  • 元素中添加属性需要使用 v-bind 绑定,简写成 “:”。

  • 使用图片要添加 mode="widthFix"。

事件绑定

事件绑定 uni-app 和 Vue 也是一模一样的,可以把事件绑定在 button 按钮、view 组件、image 组件等,例如实现单击图片时控制台输出 title 内容。

视图层代码如下。

<view class="content">
    <image :src="imgPath" mode="widthFix" @click="getData"></image>
</view>
html

M 层代码如下。

export default {
  data() {
    return {
      title: 'hello',
      imgPath: '../../static/logo.png'
    }
  },
  onLoad() {
  },
  methods: {
    getData() {
      console.log(this.title)
    }
  }
}
html

代码解析如下。

在 methods 中定义方法,如果要调用 data 中的数据,需要使用 this 获取。