uniapp中的数据绑定
1. 前言
在实际开发过程中,data 中定义的变量发生改变后,页面的数据也需要实时更新是一个很常见需求。这个需求的应用就是数据绑定的知识。
数据绑定还有许多其他的应用场景,也有多种表现形式。本小节我们来学习一下各种数据绑定的场景以及应用。
2. 插值表达式 {{}}
<template>
<!-- 插值表达式中放入 imooc 这个 data 变量,当 imooc 值发生改变时,页面上面的值也会实时更新 -->
<span> {{ imooc }} </span>
</template>
<script>
export default{
data(){
imooc: '网'
}
}
</script>
在插值表达式中也可以使用表达式。
实例:
<span>{{ 1+1 }}</span>
<span>{{ flag ? '我是网': '我不是网' }}</span>
3. v-bind 动态绑定属性
<template>
<view>
<!-- 完整语法 -->
<image v-bind:src="imgurl"/>
<!-- 缩写 -->
<image :src="imgurl"></image>
<!-- 也可以使用表达式。当isShow 变量为 true 时,显示图片;为 false 时,不显示图片 -->
<image :src="isShow ? imgurl : '' "></image>
</view>
</template>
<script>
export default{
data(){
imgurl:'/static/imooc.png',
isShow:true
}
}
</script>
也可以使用 v-bind 来做动态样式的绑定。
实例:
<template>
<view>
<view :class="isRed ? 'font-red' : 'font-green'" >
{{isRed ? "我是红色" : "我是绿色"}}
</view>
</view>
</template>
<script>
export default {
data() {
return {
isRed:false,
}
}
}
</script>
<style>
.font-red{
color: red;
}
.font-green{
color: green;
}
</style>
4. v-on 事件绑定属性
我们用 v-on 来进行 HTML 事件绑定,事件函数定义在 methods 中,v-on: 可以省略写为 @。
实例:
<template>
<view>
<!-- 完整语法 -->
<button v-on:click="showName()">点我显示名字</button>
<!-- 简写 -->
<button @click="showName()">点我显示名字</button>
</view>
</template>
<script>
export default{
methods: {
showName () {
console.log("我是imooc")
}
}
}
</script>
5. v-for 循环绑定属性
<template>
<view>
<view v-for="(item,index) in arr" :key="index">
我的名字是:{{item.name}},我{{item.age}}岁啦~
</view>
</view>
</template>
<script>
export default{
data(){
arr: [{
name: "小",
age:
},
{
name: "大",
age: ,
},
{
name: "老",
age: ,
}
]
}
</script>
会在页面上面打印下面的信息:
我的名字是:小,我5岁啦~
我的名字是:大,我25岁啦~
我的名字是:老,我55岁啦~
6. 表单控件绑定
6.1 <input>
表单元素
使用 v-model 实现这些标签数据的双向绑定。
实例:
<template>
<view>
输入名称: <input @input="replaceInput" v-model="changeValue">
</view>
</template>
<script>
export default {
data() {
return {
changeValue:"我是"
}
}
}
</script>
6.2 <picker>
普通选择器
也就是 H5 的 select 标签,用 :value 绑定 data 变量,当选项发生变化时,绑定的 data 变量 index 也会发生变化。
实例:
<template>
<view>
<picker @change="chooseName" :value="index" :range="names">
<view>
我的名字是:{{names[index]}}
</view>
</picker>
</view>
</template>
<script>
export default {
data () {
return {
index: ,
names: ['小', '大', '老']
}
},
methods: {
chooseName (e) {
console.log("当前选择名字的索引是:",e.detail.value)
}
}
}
</script>
属性说明:
6.3 <radio-group>
单项选择器
<template>
<view>
<radio-group class="radio-group" @change="radioChange">
<label class="radio" v-for="(item, index) in items" :key="item.name">
<radio :value="item.name" :checked="item.checked"/> {{item.value}}
</label>
</radio-group>
</view>
</template>
<script>
export default {
data () {
return {
items: [
{name: '0', value: '小'},
{name: '1', value: '大', checked: 'true'},
{name: '2', value: '老'}
]
}
},
methods: {
radioChange (e) {
console.log('radio发生change事件,携带value值为:', e.target.value)
}
}
}
</script>
7. 小结
本节课程我们主要学习了 uni-app 中几种类型的数据绑定。本节课程的重点如下: