我是流星的新手。我正在尝试使下拉菜单依赖于其他下拉菜单。第一个用于客户集合中的客户端名称,第二个用于地址集合中的客户端地址。我有 2 个集合客户和地址。这是我的代码,但不知道下一步该怎么做。
编辑:我将两个模板都放在另一个名为"新订单"的模板中
.HTML:
<template name="selectClient">
Client Name :
<select class="select">
<option selected disabled>Choose client name</option>
{{#each custom}}
<option>{{clientName}}</option>
{{/each}}
</select>
</template>
<template name="selectAddress">
Address:
<select class="select" name="Choose the address">
<option selected disabled>Choose the address</option>
{{#each address}}
<option>{{addressName}}</option>
{{/each}}
</select>
</template>
主.js
Template.selectClient.helpers({
'custom': function(){
return Customers.find();
}
});
Template.selectAddress.helpers({
'address': function(){
return Addresses.find();
}
});
var clientName= $('[name="newName"]').val();
var mobNumber = $('[name="newMob"]').val();
var age = $('[name="age"]').val();
var radioValue= $('[name="gender"]').val();
Customers.insert({
clientName: clientName,
age: age,
radioValue:gender,
createdAt: new Date()
});
var addressName = $('[name="addressName"]').val();
var detail = $('[name= details]').val();
Addresses.insert({
addressName: addressName,
detail: detail,
createdAt: new Date()
});
Customers = new Mongo.Collection('customers');
Addresses = new Mongo.Collection('addresses');
Mobile = new Mongo.Collection('mobile');
由于您并行使用两个模板(而不是父子关系(,因此您可以使用ReactiveVar
来缓存当前选定的客户端名称:
const selectedCustomer = new ReactiveVar()
请注意,它需要可供两个模板访问。要么在一个文件中使用两个模板声明它,要么使用import
/export
来提供对多个文件的访问权限。
现在您的客户select
需要为每个option
分配一个value
,以便我们可以在选择更改时缓存它:
<template name="selectClient">
Client Name :
<select class="select-customer">
<option selected disabled>Choose client name</option>
{{#each custom}}
<option value="clientName" selected="{{#if selectedClient clientName}}selected{{/if}}">{{clientName}}</option>
{{/each}}
</select>
</template>
为了防止命名混淆,我将其重命名为select-customter
。注意到{{#if selectedClient}}...
代码了吗?我们将使用帮助程序在下拉列表中恢复上次选择的状态。否则,您的下拉选择将在下一个渲染周期重置:
Template.selectClient.helpers({
'custom': function(){
return Customers.find();
},
selectedClient(name) {
const selected = selectedCustomer.get()
return selected && selected.clientName === name
}
});
我们从缓存中获取选定的客户,并检查当前选项的值是否相同。如果为 true,我们可以将该选项标记为selected
.
现在,您仍然需要一个涵盖所选客户端的事件:
Template.selectClient.events({
'change .select'(event, templateInstance) {
// get the value using jQuery
const value = templateInstance.$(event.currentTarget).val()
// update the ReactiveVar
selectedCustomer.set({ clientName: value })
}
})
它以可查询的格式保存所选值(当前为clientName
(。现在,在您的地址中,您只需要使用缓存的选定客户端查询所有Adresses
文档:
Template.selectAddress.helpers({
'address': function(){
const query = selectedCustomer.get() || {}
return Addresses.find(query);
}
});
如果选择客户端,它将服务器作为查询,否则将返回所有地址。
好消息是,这个ReactiveVar
已经为您提供了在更新时触发新渲染周期的功能,因为您的帮助程序的代码依赖于它,并且 Blaze 会自动为您解决此问题。
修饰
性此代码假定Adresses
与名为clientName
的字段Customers
有关系。如果使用其他字段(如_id
-clientId
(存储了关系,则需要相应地修改代码。
您也可以隐藏第二个下拉列表,如果selectedCustomer
中有值,则仅显示它。