this 指的是什么?

在 UniApp 中:

  • this 是指 Vue 页面实例

  • this.animate 报错是因为 Vue 的实例上并没有 animate() 这个方法

  • this.$scope微信小程序页面的原始 Page 对象实例,在 onReady 之后被 Vue 注入到了 Vue 实例中

this.$scope.animate() 从哪来的?

来源于微信小程序原生 API:

当 UniApp 编译为微信小程序时,会把 Vue 页面编译成一个 Page({ ... }) 结构(原生小程序结构),微信官方提供了 Page.prototype.animate() 方法

但实际运行时你会发现,Page.animate() 是个微信运行时“注入”的快捷 API,而 Vue 实例(即 this)并不会自动暴露它,只有 this.$scope 才能访问到原生 Page 上的 API(包括 animate())。

使用场景

  • 仅适用于 微信小程序平台(不支持 App/H5)

  • 自定义组件页面中通过 $scope.animate() 执行动画,常用于 transition、滑动、消失等效果

  • 不用设置 animationData,直接对节点动画

语法结构

this.$scope.animate(
selector, // 选择器
keyframes, // 动画帧数组
duration, // 动画持续时间(ms)
callback // 动画完成后的回调函数
)

参数详解

参数 类型 说明
selector String 元素选择器,例如 #box
keyframes Array<Object> 动画帧列表,每个对象定义一次属性过渡
duration Number 动画持续时间(毫秒)
callback Function 动画完成后的回调函数

示例

this.$scope.animate(
‘#box’,
[
{ opacity: 1, transform: ‘scale(1)’ },
{ opacity: 0.3, transform: ‘scale(0.5)’ }
],
500,
function () {
console.log(‘动画结束’);
}
);

优缺点

优点 缺点
操作直接、简洁 仅支持微信小程序平台
不需要 animationData 绑定 不适用于 Vue 生命周期 / App 平台
支持链式多帧动画 控制不如 createAnimation 灵活

常见错误提示

this.$scope 为 undefined?

  • 你可能在 Vue 组件中直接用 this.animatethis.$scope,这不是标准写法。

  • 解决方法this.$scope 通常只在页面生命周期中可用,建议在 onReady()mounted() 后使用。

this.clearAnimation is not a function

  • clearAnimation() 不是 Vue 实例方法,必须用 wx.clearAnimation({ selector }) 代替(仅微信小程序端支持)

实际使用建议

  • 如果你是只面向 微信小程序开发,需要快速给某个元素加动画效果,可以使用 this.$scope.animate()

  • 如果你需要 跨端兼容(App/H5)或动画逻辑较复杂(循环/控制),推荐使用 uni.createAnimation()

作者 admin

百度广告效果展示