一.使用ref定義響應式變量
在組合式 API 中,推薦使用?ref()?函數來聲明響應式狀態,ref()
?接收參數,并將其包裹在一個帶有?.value
?屬性的 ref 對象中返回
示例代碼:
<template> <view>{{ num1 }}</view><view>{{ num2 }}</view><view>{{ str }}</view><view>{{ arr[2] }}</view><view>{{obj.name}}</view>
</template><script setup>import {ref} from "vue"let num1 = 6let num2 = ref(10)//使用定時器改變num2的值// setInterval(()=>{// num2.value++;// console.log(num2.value)// },1000)//定義字符串let str = "Hello,Uni-app"//定義數組let arr = ref([1,2,3])//定義對象let obj = ref({"name":"Tim","age":18})//修改對象某個屬性的值obj.value.name = "Jim"</script>
效果:
二.v-bind指令
可簡寫為一個冒號:
冒號后面接屬性名,比如id,class,style。
示例代碼:
<template><view><image :src="picUrl"></image></view>
</template><script setup>import {ref} from "vue"let arr = ref(["/static/pic1.png","/static/pic2.png","/static/pic3.webp","/static/pic4.jpg"])const picUrl = ref("/static/pic1.png")let i = 0setInterval(()=>{i++picUrl.value=arr.value[i%4]},1000)
</script><style lang="scss"></style>
class類和style內聯樣式綁定
<view class="box" :class="isActive?'active':''"> v-bind指令</view>
<view class="box" :style="{width:'300px',height:260+'px',fontSize:size+'px'}"> 內聯指令</view>
const isActive = ref(false)
const size = ref(30)
setInterval(()=>{i++isActive.value=!isActive.value//size.value+=i
},1000)//css代碼
<style lang="scss">.box{background: orange;width: 200px;height: 200px;font-size: 20px;}.active{background: green;color: #fff;}
</style>