記錄一下用mpvue開發(fā)微信小程序遇到的問題
背景是小程序上需要寫一個簡單的循環(huán)動畫,試了幾種方法,留下了一堆坑,之后如果有空或者又遇到這個問題了再填吧(跑)
1.wx.createAnimation
先調(diào)用createAnimation API創(chuàng)建一個動畫實(shí)例animation。調(diào)用實(shí)例的方法來描述動畫。最后通過動畫實(shí)例的export方法導(dǎo)出動畫數(shù)據(jù)傳遞給組件的 animation 屬性。官方文檔的例子如下:
<view animation="{{animationData}}" style="background:red;height:100rpx;width:100rpx"></view>
Page({
data: {
animationData: {}
},
onShow: function () {
var animation = wx.createAnimation({
duration: 1000,
timingFunction: 'ease',
})
this.animation = animation
animation.scale(2,2).rotate(45).step()
this.setData({
animationData:animation.export()
})
setTimeout(function() {
animation.translate(30).step()
this.setData({
animationData:animation.export()
})
}.bind(this), 1000)
}
})
mpvue和小程序原生的寫法稍微有點(diǎn)不同:
<div :animation="animationData"></div>
const app = new Vue({
data: {
animationData: {}
},
onShow () {
let animation = mpvue.createAnimation({
duration: 1000,
timingFunction: 'ease',
})
animation.scale(2,2).rotate(45).step()
this.animationData = animation.export()
}
})
大體上都是相同的,不一樣的地方在于mpvue沒有this.animation,因?yàn)樵男〕绦騮his指的是最外面的Page,而mpvue中this指的是外層vue對象,兩者雖然看起來一樣,但是指向不同,編譯以后會報錯(暫時沒有解決mpvue中不能使用微信小程序的this.animation的問題,這個坑,之后有空再填orz),但是可以直接把創(chuàng)建的動畫實(shí)例animation賦值給已經(jīng)綁定在動畫節(jié)點(diǎn)上的this.animationData,就可以該元素的動畫效果了,我暫時沒有搞明白為什么原生小程序還需要給this.animation賦值一個動畫實(shí)例,明明可以直接給綁定在動畫節(jié)點(diǎn)上的變量賦值實(shí)現(xiàn)動畫效果(留個坑)
2.關(guān)鍵幀動畫
從小程序基礎(chǔ)庫2.9.0開始支持一種更友好的動畫創(chuàng)建方式,用于代替舊的wx.createAnimation。它具有更好的性能和更可控的接口。在頁面或自定義組件中,當(dāng)需要進(jìn)行關(guān)鍵幀動畫時,可以使用 this.animate 接口:
this.animate(selector, keyframes, duration, callback)
參數(shù)列表如下:
- selector 選擇器
- keyframes 關(guān)鍵幀信息
- duration 動畫持續(xù)時長(毫秒為單位)
- callback 動畫完成后的回調(diào)函數(shù)
之前已經(jīng)說了,在mpvue里面的this和原生小程序中的this不同,所以就不能直接使用this.animate接口(暫時不知道怎么在mpvue中直接使用this.animate接口,留個坑)
舉個在原生小程序里使用的例子:
<div id="container"></div>
Page({
data: {
animationData: {}
},
onShow: function() {
this.animate('#container', [
{ opacity: 1.0, rotate: 0, backgroundColor: '#FF0000' },
{ opacity: 0.5, rotate: 45, backgroundColor: '#00FF00'},
{ opacity: 0.0, rotate: 90, backgroundColor: '#FF0000' },
], 5000, function () {
this.clearAnimation('#container', { opacity: true, rotate: true }, function () {
console.log("清除了#container上的opacity和rotate屬性")
})
}.bind(this))
}
})
調(diào)用animate API 后會在節(jié)點(diǎn)上新增一些樣式屬性覆蓋掉原有的對應(yīng)樣式。如果需要清除這些樣式,可在該節(jié)點(diǎn)上的動畫全部執(zhí)行完畢后,在回調(diào)函數(shù)中使用this.clearAnimation清除這些屬性。
3.css3動畫
看了一圈發(fā)現(xiàn)原生小程序的動畫對mpvue不是很友好,而且只能執(zhí)行一次,要想循環(huán)還需要寫定時器,所以還可以直接選擇用css3動畫來寫:
div {
animation: animation 1s;
}
@keyframes animation {
from {background: red;}
to {background: yellow;}
}
OK,一下子就搞定了
看了看文檔,寫完以后還是對小程序動畫一知半解,留下了不少坑沒有解決,希望之后會把這些坑補(bǔ)上orz。如果上面有什么寫的不對的地方或者想法可以指正