[英]How to fix “Exception in template helper: ReferenceError: Todos is not defined” error in meteor.js
我已經在Udemy開始了完整的堆棧開發課程,並且有一個流星區。 編譯代碼時,出現以下錯誤:“模板助手中的異常:ReferenceError:未定義Todos”。
我試過在stackoverflow中搜索分辨率,但是似乎都不起作用。
我試圖用“ body”來命名模板,這是建議之一。
這就是我得到的。
客戶端/ main.js
import { Template } from 'meteor/templating';
import { Todos } from '/lib/collections';
import './main.html';
Template.main.helpers({
title(){
return 'QuickTodos';
},
todos(){
const todos = Todos.find();
return todos;
}
});
Template.main.events({
'submit .add-todo'(event){
event.preventDefault();
const text = event.target.text.value;
const time = event.target.time.value;
Todos.insert({
text,
time
});
event.target.text.value = '';
event.target.time.value = '';
}
});
Template.todo.events({
'click .toggle-checked'(event){
Todos.update(this._id, {
$set:{checked: !this.checked}
});
},
'click .delete'(event){
Todos.remove(this._id);
}
});
client / main.html
<head>
<title>QuickTodos</title>
</head>
<body>
{{> main}}
</body>
<template name="main">
<header>
<h1>{{title}}</h1>
<form class="add-todo">
<input type="text" name="text" placeholder="Add Todo...">
<input type="text" name="time" placeholder="Add Time...">
<button type="submit">Add</button>
</form>
</header>
<ul>
{{#each todos}}
{{> todo}}
{{/each}}
</ul>
</template>
<template name="todo">
<li class="{{#if checked}}checked{{/if}}">
<button class="delete">×</button>
<input type="checkbox" checked={{checked}} class="toggle-checked">
<strong>{{time}}:</strong> {{text}}
</li>
</template>
lib / collections.js
import { Mongo } from 'meteor/mongo';
export const Todos = new Mongo.Collection('todos');
現在編譯時沒有錯誤,但是當我在瀏覽器控制台中搜索Todos.find().fetch()
時,出現此錯誤:
Uncaught ReferenceError: Todos is not defined
at <anonymous>:1:1
您需要從collection.js導出Todos並將其導入到client / main.js文件中// //在您的lib / collection文件中執行此操作
import { Mongo } from "meteor/mongo";
const Todos = new Mongo.Collection("todos");
export default Todos;
在您的main / server.js文件中,您需要導入Todos
import Todos from "../lib/collections";
還可以在您的client / main.js文件中導入Todos
import Todos from "../lib/collections";
完成上述操作后,即可看到待辦事項。 干杯
嗨,您有兩個簡單的解決方案。
1.改變
const Todos = new Mongo.Collection('todos');
至
Todos = new Mongo.Collection('todos');
在lib / collections.js中,這將使Todos集合具有全局性,因此可以從您的模板進行訪問。
2.如果您不希望使用全局范圍的變量,請執行以下操作。 更改
const Todos = new Mongo.Collection('todos');
至
export const Todos = new Mongo.Collection('todos');
在lib / collections.js中
添加到文件頂部client / main.js
import {Todos} from '/lib/collections';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.