I have a login system with the following layout :
<template name="loginLayout">
<div class="container">
<div class="flat-form">
<ul class="tabs">
<li> <a id="login" class="{{#if isRouteActive 'login' }}active{{/if}}" href="{{ pathFor 'login' }}">Login</a> </li>
<li> <a id="registration" class="{{#if isRouteActive 'registration' }}active{{/if}}" href="{{ pathFor 'registration' }}">Register</a> </li>
<li> <a id="resetPassword" class="{{#if isRouteActive 'resetPassword' }}active{{/if}}" href="{{ pathFor 'resetPassword' }}">Reset Password</a> </li>
</ul>
{{> yield }}
</div>
</div> </template>
According to which link a user hits, meteor renders the correct template in the yield field.
This works fine, but when a user logs in, the private page is rendered within this layout which is wrong. I don't understand why this is happening, if I specify the layout only for the login routes.
Routes file :
Router.map( function () {
this.route( 'login',
{
path : '/login',
layoutTemplate: 'loginLayout',
yieldTemplate : 'login',
data : {
appName : "test",
welcomeMessage : "test."
}
}
);
this.route( 'registration',
{
path : '/registration',
layoutTemplate: 'loginLayout',
yieldTemplate:'registration',
data : {}
}
);
this.route( 'resetPassword',
{
path : '/resetPassword',
layoutTemplate: 'loginLayout',
yieldTemplate : 'resetPassword',
data : {}
}
);
this.route('library');
});
var mustBeSignedIn = function(pause) {
if (!(Meteor.user() || Meteor.loggingIn())) {
Router.go('login');
pause();
}
};
Router.onBeforeAction(mustBeSignedIn, {except: ['login', 'registration', 'resetPassword']});
Login.js
Template.login.events({
'submit #login-form' : function(e, t){
e.preventDefault();
// retrieve the input field values
var userName = t.find('#login-email').value
, password = t.find('#login-password').value;
Meteor.loginWithPassword(userName, password, function(err){
if (err) {
console.log("Error when loggin ");
console.log(err.reason);
} else {
console.log("user logged in");
/***** REDIRECT ******/
Router.go('library');
}
});
return false;
}
});
logi.js template :
<template name="login">
<div id="login" class="form-action">
<h1>Login on {{ appName }} </h1>
<p> {{ welcomeMessage }} </p>
<form id="login-form">
<ul>
<li> <input id="login-email" type="text" placeholder="Username" /></li>
<li> <input id="login-password" type="password" placeholder="Password" /></li>
<li> <input id="submit" type="submit" value="Login" class="button" /></li>
</ul>
</form>
</div>
</template>
I have also noticed that when I use the method "go" to redirect a user to a given route, the data field is reset. Whereas, when I write down the url every thing works fine.
Full source
The way it worked for me was to create an additional controller for my major layout and render my header and footer template again with and layoutTemplate, yieldTemplate and action: function(){}.
Here an example route:
Router.route('einstellungen', function() { // settings
this.render('Settings', {
to: 'interfaceContainer'
});
}, {
controller: 'InterfaceController'
});
And only after adding the following code, Router.go('/einstellungen'); works in a way that the entire layout plus yield layouts are rendered.
InterfaceController = RouteController.extend({
layoutTemplate: 'interfaceLayout',
yieldTemplates: {
'Header': {
to: 'interfaceHeader'
},
'Footer': {
to: 'interfaceFooter'
}
},
action: function() {
this.render('Header', {
to: 'interfaceHeader'
});
this.render('Footer', {
to: 'interfaceFooter'
});
}
});
I also added:
Router.configure({
layoutTemplate: 'interfaceLayout',
yieldTemplates: {
'Header': {
to: 'interfaceHeader'
},
'Footer': {
to: 'interfaceFooter'
}
}
});
But this does not seem to have any impact on Router.go();
See also:
https://forums.meteor.com/t/custom-layout-for-a-specific-route-not-displaying-with-iron-router/5758
https://github.com/iron-meteor/iron-router/blob/devel/Guide.md#creating-route-controllers
Related
I am using Vuejs cdn. In which I have a Navigation menu. I want to load different layout when a user clicks on Nav menu.
for example
<div class="row" id="mytemplate">
<div class="col-sm-3 sidebar-col">
<div>
<nav class="settings-sidebar">
<h4>Profile settings</h4>
<ul>
<li class="active" v-on:click="Profile()">
<a >Profile picture</a>
</li>
<li class="" v-on:click="Business()">
<a >Business details</a>
</li>
<li class="" v-on:click="Equipments()">
<a >Equipments details</a>
</li>
</ul>
</nav>
</div>
</div>
<div class="col-sm-9 col-xs-12 settings-body">
{{ load_layout_here }}
</div>
Now when user click on "Business Details" option it should run function Business() and load layout from business.html or business.php
the sample code in business.php
<div class="form">
<div class="input-field">
<h5>Business name</h5>
<input type="text" class="textbox" name="primary-phone" value="Perfect choice movers" placeholder="Your business name" maxlength="15">
</div>
<div class="input-field inline-input">
<h5>City</h5>
<input type="text" class="textbox " name="business-city" value="myCity" placeholder="Business address" maxlength="15">
</div>
<button class="btn btn-orange" type="submit">Save</button>
My vue.js code is
var app2 = new Vue({
el: '#mytemplate',
data : {
message : 'hi',
},
methods: {
Profile : function () {
this.message = 'Profile';
},
Business : function () {
// Here I want to call Html Template to load seprate layout
this.message = 'Business';
},
Equipments : function () {
this.message = 'Equipments';
}
}
})
I have seen lots of answers on the internet but they all using vue template engine or .vue files. Which I do not want to use
Note : I am using CodeIgniter as PHP framework. and Vue for frontend.
You can use axios to render the html. What ever data come in response data variable. That should to show.
Profile : function () {
axios.get('profile.php')
.then(function (response) {
console.log(response.data);
// response
this.message = response.data.json;
})
.catch(function (error) {
// handle error
console.log(error);
});
}
and to use axios, you have to include cdn file.
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
I have a sidebar child component with buttons that change the tab:
<script type="text/x-template" id="employee-sidebar">
<div class="sidebar full-height col-" data-color="purple">
<div class="sidebar-wrapper" id="dash-board">
<ul class="nav">
<li v-bind:class="{ active: activeLink == 'dashboard' }">
<a href="#dashboard" #click="changeTab('dashboard')">
<i class="material-icons">dashboard</i>
<p>Dashboard</p>
</a>
</li>
<li v-bind:class="{ active: activeLink == 'team' }">
<a href="#radio" #click="changeTab('team')">
<i class="fa fa-users"></i>
<p>Team</p>
</a>
</li>
<li class="text-center"><button class="btn btn-primary clear-filter">Clear</button></li>
</ul>
</div>
</div>
</script>
When I call #click="changeTab('dashboard')" it calls a function in the child component and emits a changeTab event:
Vue.component('employee-sidebar', {
template: '#employee-sidebar',
props: {},
data: function() {
return {
activeLink: 'dashboard'
}
},
methods: {
changeTab: function(tab) {
// Always see this console log
console.log(tab)
this.activeLink = tab
this.$emit('changeTab', tab)
}
}
})
When I call the component in the parent I listen for this event:
<employee-sidebar v-on:changeTab="changeTheTab(activeLink)"></employee-sidebar>
But the changeTheTab() function is never called in the parent:
changeTheTab: function(tab) {
// Never see this console log
console.log(tab)
this.activeLink = tab
}
What am I doing wrong?
Thanks to #wostex for the lowercase tip, I was able to update my component to the following:
Vue.component('employee-sidebar', {
template: '#employee-sidebar',
props: {},
data: function() {
return {
activeLink: 'dashboard'
}
},
methods: {
changeTab: function(tab) {
console.log(tab)
this.activeLink = tab
this.$emit('change_tab', tab)
}
}
})
and in the parent:
<employee-sidebar v-on:change_tab="(tab) => activeLink = tab"></employee-sidebar>
I have a parent component in Vue.js which looks like this:
<template>
<ul class="list-group">
<li class="list-group-item" v-for="item in items">
<div class="row">
<div class="col-md-6">
{{ item.title }}
</div>
<div class="col-md-6 text-right">
<a href="#" class="btn btn-primary btn-sm">
<span class="glyphicon glyphicon-pencil"></span>
</a>
<a href="#" class="btn btn-success btn-sm">
<span class="glyphicon glyphicon-link"></span>
</a>
<a href="#" class="btn btn-danger btn-sm">
<span class="glyphicon glyphicon-remove"></span>
</a>
</div>
<div class="col-md-12">
<preview></preview>
</div>
</div>
</li>
</ul>
</template>
The script:
<script>
import Preview from './Preview.vue';
export default {
data() {
return {
items: '',
template: []
}
},
created() {
this.fetchItems();
this.$on('preview-build', function (child) {
console.log('new preview: ')
console.log(child)
})
},
components: {
Preview
},
methods: {
fetchItems: function () {
var resource = this.$resource('api/preview');
resource.get({}).then((response) => {
this.items = response.body.item;
}, (response) => {
console.log('Error fetching tasks');
}).bind(this);
},
}
}
</script>
The child component "preview" has a template-like structure, for example {{ item.title }} again. The preview is loaded correct but it's not rendered.
I really do not know if it is possible in Vue 2.0 but hopefully someone had the same problem and can help me here.
EDIT (thanks Patrick):
<template>
<textarea rows="20" class="form-control">
{{ template.content }}
</textarea>
</template>
<script>
export default {
data() {
return {
template: [],
}
},
created() {
this.fetchTemplate();
},
methods: {
fetchTemplate: function () {
var resource = this.$resource('api/preview');
resource.get({}).then((response) => {
this.template = response.body.template;
}, (response) => {
console.log('Error fetching template');
}).bind(this);
},
}
}
</script>
This is the Preview.vue content which is similar to the Item.vue content.
As a little explanation:
The template data comes from an database as predefined html content including the {{ item.title }} and some other placeholder. I want this to be rendered with the specific stuff coming from the item.
In Vue.js, components can't directly access data from their parent. If you want preview to be able to render {{ item.title }}, you'll have to pass item down to it as a prop. So in preview.vue, declare it like this:
export default {
...
props: ['item']
}
Then, in your parent component's template, you can v-bind that item prop to something from the parent's items array:
<li class="list-group-item" v-for="item in items">
...
<preview v-bind:item="item"></preview>
...
</li>
Now your preview component has an item that it can render in its template as if it were part of the data object.
I'm sure this one's gonna be extremely easy for you guys. I am trying to make a simple list of posts with the post titles always visible, and when you click a specific post in the list, you get the post's body. I used v-show for that. However, when I click a specific post, the bodies of all of the posts appear, instead of just the one that I clicked.
Here's the template:
<template>
<div class="container">
<h1>My Posts</h1>
<ul class="list-group">
<li class="list-group-item" v-for="post in list">
<div #click="changeShow">
<h4>{{ post.title }}</h4>
<p v-show="show">{{ post.body }}</p>
<span v-show="show" class="label label-primary">ID: {{ post.userId }}</span>
</div>
</li>
</ul>
</div>
And the logic:
<script>
export default{
data(){
return{
msg:'hello vue',
list: [],
show: false
}
},
ready(){
this.fetchPostList();
},
methods:{
fetchPostList: function () {
var root = 'http://jsonplaceholder.typicode.com';
this.$http.get(root + '/posts').then(function (response) {
this.list = response.data;
})
},
changeShow: function () {
this.show = !this.show;
}
}
}
There's a few ways to approach this depending on your needs.
Multiple Open
You can make each post it's own component, that way you can have show be tied to each individual post instead of all of them.
Vue.component('post', {
template: '#post-template',
props: {
post: Object,
},
data() {
return {
show: false,
}
},
methods: {
toggleShow() {
this.show = !this.show
},
},
})
Then you can have use it like this:
<post v-for="post in posts" :post="post"></post>
One Open
If you just want one open you can pass an id as a prop and show it based on that.
Vue.component('post', {
template: '#post-template',
props: {
post: Object,
selectedId: Number,
},
computed: {
show() {
return this.post.id === this.selectedId
},
},
})
Then you can do like
<post :selected-id="selectedId" :post="post" #click="selectedId = post.id"></post>
I cheated in a different way. Just added a show property to each post and toggled that.
new Vue({
el: 'body',
data: {
list: []
},
ready: function() {
this.fetchPostList()
},
methods: {
fetchPostList: function() {
setTimeout(function() {
this.list.push({
title: 'First Post',
body: 'This is the first Post',
userId: 'Joe',
show: false
});
this.list.push({
title: 'Second Post',
body: 'This is the second Post',
userId: 'Joe',
show: false
});
this.list.push({
title: 'Third Post',
body: 'This is the third Post',
userId: 'Joe',
show: false
});
}.bind(this), 2000);
},
changeShow: function(idx) {
this.list[idx].show = !this.list[idx].show;
}
}
});
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<div class="container">
<h1>My Posts</h1>
<ul class="list-group">
<li class="list-group-item" v-for="post in list">
<div #click="changeShow($index)">
<h4>{{ post.title }}</h4>
<p v-show="post.show">{{ post.body }}</p>
<span v-show="post.show" class="label label-primary">ID: {{ post.userId }}</span>
</div>
</li>
</ul>
</div>
First of all, the method that I will give an example is not useful, but I am writing to show that there is such a way.
for example
<script>
export default {
data: {
isShow: false,
postUserId: null,
},
};
</script>
<template>
<div class="container">
<h1>My Posts</h1>
<ul class="list-group">
<li class="list-group-item" v-for="post in list">
<div #click="postUserId = post.userId; isShow = !isShow">
<h4>{{ post.title }}</h4>
<p v-show="show">{{ post.body }}</p>
<span v-show="isShow && postUserId == post.userId" class="label label-primary">ID: {{ post.userId }}</span>
</div>
</li>
</ul>
</div>
</template>
I'm using Intellij and Meteor to make an application and I'm trying to use Iron Router to create multiple pages, but when I call the Router in the Javascript file, it says that Router is an unresolved variable and that route is an unresolved function or method. I've checked the meteor folder and it appears that all the Iron Router files loaded fine. At the bottom of the root page I am working on it says
Oops, looks like there's no route on the client or the server for url:
"http://localhost:3000/."
If I navigate to http://localhost:3000/about, which is the only page I have a route set up for yet, the page is blank, except for my nav bar.
Here is my javascript file...
Items = new Mongo.Collection("items");
Found_items = new Mongo.Collection("found_items");
Router.route('home', {path: '/'}); // Add this route
Router.route('about', {path: '/about'});
if (Meteor.isClient) {
// This code only runs on the client
Template.body.helpers({
items: function () {
return Items.find({});
},
found_items: function () {
return Found_items.find({});
},
priceSum: function(){
var userItems = Found_items.find({
userId: this._id
}).fetch();
var prices = _.pluck(userItems, "price");
var totalTaxed = _.reduce(prices, function(sum, price){
var total = sum + parseFloat(price);
return total + (total * 0.04712);
}, 0);
return totalTaxed.toFixed(2);
},
calcTax: function () {
var userItems = Found_items.find({
userId: this._id
}).fetch();
var prices = _.pluck(userItems, "price");
var tax = _.reduce(prices, function(sum, price){
return (sum + parseFloat(price)) * 0.04712;
}, 0);
return tax.toFixed(2);
}
});
Template.body.events({
"submit .new-item": function (event) {
event.preventDefault();
var text = event.target.text.value;
Items.insert({
text: text,
createdAt: new Date(),
owner: Meteor.userId(),
username: Meteor.user().username
});
event.target.text.value = "";
}
});
Template.item.events({
"click .found": function (event, template) {
event.preventDefault();
var price = template.find('[name="price"]').value;
var text = template.find('.text').textContent;
Items.remove(this._id);
Found_items.insert({
text: text,
price: price
});
}
});
Template.body.events({
"click .remove": function(event) {
event.preventDefault();
Found_items.remove(this._id);
}
});
Accounts.ui.config({
passwordSignupFields: "USERNAME_ONLY"
});
}
And here is the HTML file
<head>
<title>Grocery List</title>
</head>
<template name="home">
<body>
<div>
<ul class="menu">
<li class="menuItem">{{> loginButtons}}</li>
<li class="menuItem">Home </li>
<li class="menuItem">About</li>
</ul>
</div>
{{#if currentUser}}
<div class="container">
<header>
<h1 id="title">Grocery List</h1>
<form class="new-item">
<input type="text" name="text" placeholder="Type to add new items" />
</form>
</header>
<ul>
{{#each items}}
{{> item}}
{{/each}}
</ul>
</div>
<div class="container">
<header>
<h1>Items Found</h1>
</header>
<ul>
{{#each found_items}}
{{> found}}
{{/each}}
</ul>
</div>
<div class="container">
<header>
<h3>
Tax: ${{calcTax}}
</h3>
<h2>
Total: ${{priceSum}}
</h2>
<button class="save">Save list</button>
</header>
</div>
{{else}}
<h3>Please log in first.</h3>
{{/if}}
</body>
</template>
<template name="item">
<li>
<button class="found">Got it!</button>
<input type="number" name="price" placeholder="Sale Price" />
<span class="text">{{text}}</span>
</li>
</template>
<template name="found">
<li>
<button class="remove">×</button>
<span class="text">{{text}}</span>
<span class="price">{{price}}</span>
</li>
</template>
<template name="about">
<head>
<title>About Grocery List</title>
</head>
<body>
<div>
<ul class="menu">
<li class="menuItem">{{> loginButtons}}</li>
<li class="menuItem">Home </li>
<li class="menuItem">About</li>
</ul>
</div>
<div class="container">
<header><h1>About</h1></header>
<p>This application was created using Meteor. It can be used to make, save and update grocery lists. Once the user is in the store, they can use it to check off items on the list, put in the price and see the total, with tax.<br>
Users can also save their previous lists to either reuse them, or compare current prices to previous ones.<br>
Future implementations of this page would also allow the user to change the tax rate depending on their location, and include coupons and other discounts in the pricing.</p>
</div>
</body>
</template>
Always add a route for the root.
Items = new Mongo.Collection("items");
Found_items = new Mongo.Collection("found_items");
Router.route('home', {path: '/'}); // Add this route
Router.route('about', {path: '/about'});
BTW, you have a head and body section within your template. That is rendered but does not have an effect in your browser.
Use the following syntax with IR's template helper pathFor:
<ul class="menu">
<li class="menuItem">{{> loginButtons}}</li>
<li class="menuItem">Home</li>
<li class="menuItem">About</li>
</ul>
In order to get your code working, I also fixed a couple of issues:
Removed head and body tags in templates.
Renamed Template.body.helpers to Template.home.helpers.
Renamed Template.body.events to Template.home.events.
Now it is adding new items to the collection and showing items.
you have to add a route with / to call localhost:3000
routing example
Router.configure({
layoutTemplate: 'layout',
});
Router.route('/', function () {
this.render('home');
},{
name: 'home'
});
Router.route('/about', function () {
this.render('about');
},{
name: 'about'
});
html
<template name="layout">
{{> yield}}
</template>
<template name="home">
<p>i am the homepage</p>
</template>
<template name="about">
<p>i am the about page</p>
</template>