data 属性
data 必须声明为返回一个初始数据对象的函数(注意函数内返回的数据对象不要直接引用函数外的对象);否则页面关闭时,数据不会自动销毁,再次打开该页面时,会显示上次数据。
//正确用法,使用函数返回对象
data() {
return {
title: 'Hello'
}
}
//错误写法,会导致再次打开页面时,显示上次数据
data: {
title: 'Hello'
}
//错误写法,同样会导致多个组件实例对象数据相互影响
const obj = {
title: 'Hello'
}
data() {
return {
obj
}
}
Class 与 Style 绑定
为节约性能,我们将 Class
与 Style
的表达式通过 compiler
硬编码到 uni-app
中,支持语法和转换效果见下:
对象语法:
可以传给 v-bind:class 一个对象,实现动态地切换 class。
也可以在对象中传入更多字段来动态切换多个 class。此外,v-bind:class 指令也可以与普通的 class 共存。
<template>
<view>
<!-- class -->
<view class="static" :class="{ active: isActive}">111</view>
<view class="static" :class="{ active: isActive, 'text-danger': hasError }">222</view>
<!-- style -->
<view v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">333</view>
</view>
</template>
<script>
export default {
data() {
return {
isActive: true,
hasError: false,
activeColor:"green",
fontSize:50
}
}
}
</script>
<style>
.static{
color: #2C405A;
}
.active{
background-color: #007AFF;
}
.text-danger{
color: #DD524D;
}
</style>
数组语法
可以把一个数组传给 v-bind:class,以应用一个 class 列表。
<template>
<view>
<!-- class -->
<view class="static" :class="[activeClass,errorClass]">111</view>
<view class="static" v-bind:class="[isActive ? activeClass : '', errorClass]">222</view><!-- 三元表达式 -->
<view class="static" v-bind:class="[{ active: isActive }, errorClass]">333</view>
<!-- style -->
<view v-bind:style="[{ color: activeColor, fontSize: fontSize + 'px' }]">444</view>
</view>
</template>
<script>
export default {
data() {
return {
isActive: true,
activeClass: 'active',
errorClass: 'text-danger',
activeColor:"green",
fontSize:50
}
}
}
</script>
<style>
.static{
font-size:30rpx;
}
.active{
background-color: #007AFF;
}
.text-danger{
font-size:60rpx;
color:#DD524D;
}
</style>
条件渲染
v-if和v-else
v-if
指令用于条件性地渲染一块内容。这块内容只会在指令的表达式返回 truthy
值的时候被渲染。 使用 v-else
指令来表示 v-if 的“else 块”。
<template>
<view>
<view v-if="seen">现在你看到我了</view>
<view v-else>你看不到我了</view>
</view>
</template>
<script>
export default {
data() {
return {
seen: true
}
}
}
</script>
v-else-if
,顾名思义,充当 v-if 的“else-if 块”,可以连续使用:
<template>
<view>
<view v-if="type === 'A'">
A
</view>
<view v-else-if="type === 'B'">
B
</view>
<view v-else-if="type === 'C'">
C
</view>
<view v-else>
Not A/B/C
</view>
</view>
</template>
<script>
export default {
data() {
return {
type:'B'
}
}
}
</script>
类似于 v-else
,v-else-if
也必须紧跟在带 v-if
或者 v-else-if
的元素之后。
未完,明天继续写。