我想将我的 EmberJS 应用程序的单一路线用作多步骤表单。这是我唯一一次希望我的 URL 保持不变,因此 location: 'none'
不是一个选项(据我所知)。我在其他路由上有 Controller ,它们应该与 URL 紧密集成。
但在这个单一的、不变的 URL 上,我想完成以下任务:
- 用户回答了一些问题。
- 用户点击按钮,旧问题就会被新问题替换。
- 冲洗并重复,直到最后一个“页面”,所有数据最终在提交时进行
.save()
编辑。
Handlebars 的工作方式真的让我感到困惑。
我一直在翻阅文档,但找不到真正的示例。我有一种感觉,这是一种我不知道我还不知道的事情。因此,如果有人能给我指出正确的方向,希望这就是我所需要的。
最佳答案
我从 MartinElvar 的 excellent answer 开始,但最终出现在不同的地方,因为我需要验证向导每一页上的表单。通过将向导的每个页面设为自己的组件,您可以轻松限制每个页面的验证。
从 Controller 上的步骤列表开始:
// app/controllers/wizard.js
export default Ember.Controller.extend({
steps: ['stepOne', 'stepTwo', 'stepThree'],
currentStep: undefined
});
然后确保每当输入 Controller 时,将用户引导至第一步:
// app/routes/wizard.js
export default Ember.Route.extend({
setupController (controller, model) {
controller.set('currentStep', controller.get('steps').get('firstObject');
this._super(controller, model);
}
});
现在您可以返回 Controller 并添加一些更通用的下一步/后退/取消步骤:
// app/controller/wizard.js
export default Ember.Controller.extend({
steps: ['step-one', 'step-two', 'step-three'],
currentStep: undefined,
actions: {
next () {
let steps = this.get('steps'),
index = steps.indexOf(this.get('currentStep'));
this.set('currentStep', steps[index + 1]);
},
back () {
let steps = this.get('steps'),
index = steps.indexOf(this.get('currentStep'));
this.set('currentStep', steps.get(index - 1));
},
cancel () {
this.transitionToRoute('somewhere-else');
},
finish () {
this.transitionToRoute('wizard-finished');
}
}
});
现在为向导的页面定义一个组件。这里的技巧是使用与 Controller 中列出的每个步骤相同的名称来定义每个组件。 (这允许我们稍后使用组件帮助器。)这部分允许您在向导的每个页面上执行表单验证。例如,使用 ember-cli-simple-validation :
// app/components/step-one.js
import {ValidationMixin, validate} from 'ember-cli-simple-validation/mixins/validate';
export default Ember.Component.extend(ValidationMixin, {
...
thingValidation: validate('model.thing'),
actions: {
next () {
this.set('submitted', true);
if (this.get('valid')) {
this.sendAction('next');
}
},
cancel () {
this.sendAction('cancel');
}
}
});
最后,路线的模板变得简单:
// app/templates/wizard.hbs
{{component currentStep model=model
next="next" back="back" cancel="cancel" finish="finish"}}
每个组件都会获取对 Controller 模型的引用,并在步骤中添加所需的数据。这种方法对我来说非常灵活:它允许您在向导的每个阶段执行任何必要的疯狂操作(例如与硬件交互并等待它响应)。
关于ember.js - 使用 Ember.js 在一条 route 实现多步骤形式(或多个 "pages"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21620782/