跟随Ember.js教程实践时{{on}}修饰符运行触发解析报错
报错原因
两处问题触发构建失败:
- 模板事件绑定语法错误:
image.hbs中使用{{on}}绑定点击事件时,给回调函数toggleSize错误添加了调用括号()。{{on}}修饰符需要接收函数引用作为事件触发时的执行回调,加括号会导致模板渲染阶段就直接执行该函数,同时将函数返回值(此处为undefined)传给事件监听器,直接触发语法解析错误。 - 构建路径提示异常:报错提示错误出在
image.js是构建工具的路径识别偏差,你贴出的image.js代码本身没有语法问题,注意不要将Handlebars模板语法的内容写入.js后缀的文件即可。
修正代码
image.hbs
把两处{{on 'click' this.toggleSize()}}的括号去掉即可,修正后完整代码:
{{#if this.isLarge}} <button type="button" class='image' {{on 'click' this.toggleSize}}> <img ...attributes> <small>View Smaller</small> </button> {{else}} <button type="button" class="image" {{on 'click' this.toggleSize}}> <img ...attributes> <small>View Larger</small> </button> {{/if}}
image.js
你当前的image.js代码完全正确,无需修改:
import Component from '@glimmer/component'; import { tracked } from '@glimmer/tracking'; import { action } from '@ember/object'; export default class RentalImageComponent extends Component { @tracked isLarge = false; @action toggleSize() { this.isLarge = !this.isLarge; } }
缓存清理(改完仍报错时执行)
如果修正代码后还是出现相同解析错误,清理构建缓存后重启服务即可:
rm -rf node_modules/.cache tmp dist ember serve
内容的提问来源于stack exchange,提问作者rhtnejr
相关产品推荐
相关产品推荐

