更改Meteor应用程序文本的多个按钮

Multiple buttons that change the text of a Meteor app

本文关键字:按钮 文本 Meteor 应用程序 更改      更新时间:2023-09-26

我刚开始使用MeteorJS

如果我有一系列按钮,有没有办法根据我单击的按钮来更改页面的正文?

如果我有一个名为"Hello"的按钮,我希望正文更改为"你好"。

感谢

使用Session变量

HTML

<body>
  {{> main}}
</body>
<template name="main">
  <p>{{text}}</p>
  {{> button}}
</template>
<template name="button">
  <button type="button">Hello</button>
</template>

JS-

Template.main.onCreated(function(){
  Session.set("text", "Default");
});
Template.main.helpers({
  text: function(){
    return Session.get("text");
  }
});
Template.button.events({
  "click button": function(event, template){
    var buttonText = template.$("button").text();
    Session.set("text", buttonText);
  }
});

使用ReactiveVar来避免全局性并提供更好的组件封装

HTML也是一样的。

JS-

Template.main.onCreated(function(){
  this.text = new ReactiveVar("Default");
});
Template.main.helpers({
  text: function(){
    return Template.instance().text.get();
  }
});
Template.button.events({
  "click button": function(event, template){
    var buttonText = template.$("button").text();
    // search for a field named text in the closest parent template (main)
    template.get("text").set(buttonText);
  }
});

我们需要添加2个包才能使此代码工作:

meteor add reactive-var
meteor add aldeed:template-extension