vue.js - Organize big single page application with multiple views - javascript

I'm playing with new MVVM framework - Vue.js (http://vuejs.org/).
It was really nice in simple examples and demos but now I'm trying to create big SPA with multiple views and I'm realizing that the best pattern how to do it is not described in framework's docs.
The main problem is that I don't know how to handle views on different routes.
For example, I'm using Director (https://github.com/flatiron/director) for routing but how can I change views?
var booksCtrl = function () {
var booksViewModel = new Vue({
el: '#books'
data: { ... }
ready: function () {
// hide previous ViewModel and display this one??
}
});
};
var editBookCtrl = function (id) {
var editBookViewModel = new Vue({
el: '#editBook'
data: { ... }
ready: function () {
// hide previous ViewModel and display this one??
}
});
};
var routes = {
'/books': booksCtrl,
'/books/:id/edit': editBookCtrl
};
var router = new Router(routes);
router.init();
Do I need to create separate Vue.js ViewModels and just display:block / display:none them like in this example?
What would be the right way in your opinion? Thanks!

Nested subviews can be resolved by using v-view and v-ref.
html
<div id="main">
<div v-view="currentView" v-ref="view"></div>
</div>
<ul>
<li>top</li>
<li>nest/view1</li>
<li>nest/view2</li>
</ul>
<script id="top" type="x-template">
<div>top view</div>
</script>
<script id="nest" type="x-template">
<div>
<span>nest view</span>
<div v-view="subview"></div>
</div>
</script>
javascript
Vue.component('top', Vue.extend({
template: "#top",
}));
Vue.component('nest', Vue.extend({
template: '#nest',
components: {
view1: Vue.extend({
template: '<span>this is subview 1</span>',
}),
view2: Vue.extend({
template: '<span>this is subview 2</span>',
}),
},
data: {
subview: "view1",
},
}));
var main = new Vue({
el: "#main",
data: {
currentView: "top",
},
});
var router = new Router({
'/': function() { main.currentView = 'top' },
'/nest/:view': function(view) {
main.currentView = 'nest';
main.$.view.subview = view;
},
});
router.init();
jsfiddle: http://jsfiddle.net/koba04/WgSK9/1/

The officially recommended way to use routing in vuejs applications is to use vue-router :
Quoting from the documentation :
vue-router is the official router for Vue.js. It
deeply integrates with Vue.js core to make building Single Page
Applications with Vue.js a breeze. Features include:
Nested route/view mapping
Modular, component-based router configuration
Route params, query, wildcards
View transition effects powered by Vue.js' transition system
Fine-grained navigation control
Links with automatic active CSS classes
HTML5 history mode or hash mode, with auto-fallback in IE9
Restore scroll position when going back in history mode
The well-written documentation elaborates further on Modular, component-based router configuration, including examples on handling nested routes.
A router-view outlet is made available into which the route configuration can specify which component to render. These components can contain embedded router-view outlets allowing component oriented nested route management.
Example from the docs:
<div id="app">
<router-view></router-view>
</div>
router.map({
'/foo': {
component: Foo,
// add a subRoutes map under /foo
subRoutes: {
'/bar': {
// Bar will be rendered inside Foo's <router-view>
// when /foo/bar is matched
component: Bar
},
'/baz': {
// Same for Baz, but only when /foo/baz is matched
component: Baz
}
}
}
})

You might be able to use v-view and component?
http://vuejs.org/guide/application.html
like this.
javascript
Vue.component('top', Vue.extend({
template: "<div>top view</div>",
}));
Vue.component('other', Vue.extend({
template: "<div>other view</div>",
}));
var main = new Vue({
el: "#main",
data: {
currentView: "top",
},
});
var router = new Router({
'/': function() { main.currentView = 'top' },
'/other': function() { main.currentView = 'other' },
});
router.init();
html
<div id="main">
<div v-view="currentView"></div>
</div>

You could use Named Views if you don't want to nest them.
html
<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>
javascript
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
const Baz = { template: '<div>baz</div>' }
const router = new VueRouter({
mode: 'history',
routes: [
{
path: '/',
// a single route can define multiple named components
// which will be rendered into <router-view>s with corresponding names.
components: {
default: Foo,
a: Bar,
b: Baz
}
},
{
path: '/other',
components: {
default: Baz,
a: Bar,
b: Foo
}
}
]
})
jsfiddle: https://jsfiddle.net/posva/6du90epg/
The fiddle is from the doc: https://router.vuejs.org/en/essentials/named-views.html

Related

Proper way to use "props" in VueJS

I'm creating a new project using VueJS as first time, and trying to use a toolbar on all of my pages. But I want to make the title present in the toolbar, dynamic.
I tried to use props, but I must be wrong the way I use it. Check the example below :
In my index.html :
<div id="app" v-cloak>
<v-app>
<spa-toolbar :title="title"></spa-toolbar>
<router-view></router-view>
</v-app>
</div>
<script>
Vue.use(VueRouter);
Vue.use(VeeValidate);
Vue.config.devtools = true;
const routes = [
{
path: '/',
component: spaLogin,
props: {title: 'Connexion'}
},
{
path: '/parametres',
name : 'parametres',
component: spaParametres,
props: {title: 'Paramètres'}
},
];
let router = new VueRouter({
hashbang: false,
routes
});
router.beforeEach((to, from, next) => {
next();
});
var app = new Vue({
el: '#app',
watch: {},
data: {
title: 'Connexion',
},
router
});
</script>
toolbar.vue.js (with the "props: ["title"]) :
<v-toolbar-title class="white--text">{{title}}</v-toolbar-title>
And in another page "parametres.vue.js" I'm using the props["title"], but the value of the title is always "Connexion", the value defined in my main App in index.html.
How can I make this value dynamic ? Thought passing it through the router would be great...
Thanks !
You are passing the property title from the v-app component to the spa-toolbar component. Then you are setting a property on the routes which is also called title.
These two are not related in any way. Also the title prop from the route is passed to the component in router-view, i.e. spaLogin and spaParametre.
So I think a better way would be to define a meta field on the route:
<div id="app" v-cloak>
<v-app>
<spa-toolbar :title="(($route.matched[0] || {}).meta || {}).title"></spa-toolbar>
<router-view></router-view>
</v-app>
</div>
<script>
Vue.use(VueRouter);
Vue.use(VeeValidate);
Vue.config.devtools = true;
const routes = [
{
path: '/',
component: spaLogin,
meta: {title: 'Connexion'}
},
{
path: '/parametres',
name : 'parametres',
component: spaParametres,
meta: {title: 'Paramètres'}
},
];
let router = new VueRouter({
hashbang: false,
routes
});
var app = new Vue({
el: '#app',
data: {},
router
});
</script>

Vue Router. Bind data

I am developing vue app and now I am on step when I should use vue router.
But I have a little problem with data bind into router template.
Please help me.
HTML:
<div id="app">
<h1>Hello App!</h1>
<p>
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
</p>
<router-view></router-view>
</div>
Script:
const Foo = { template: '<div>{{foo}}</div>' }
const Bar = { template: '<div>bar</div>' }
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
const router = new VueRouter({
routes
})
const app = new Vue({
el: '#app',
router,
data: function(){
return {foo: "asdasdas"}
}
})
{{foo}} bind doesn't work.
Live example:
https://jsfiddle.net/xgrjzsup/4430/
From the guide on components :
Every component instance has its own isolated scope. This means you
cannot (and should not) directly reference parent data in a child
component’s template. Data can be passed down to child components
using props.
and Foo is a child component of your app set via the router.
One way to pass data from parent to child is to use props.
Modify your Foo definition to accept a foo property:
const Foo = {
props: ['foo'],
template: '<div>{{foo}}</div>'
}
and bind the parent property in the template
<router-view :foo="foo"></router-view>
An updated Fiddle : https://jsfiddle.net/xgrjzsup/4431/
in your case there are two ways you can access that "foo" var.
{{$parent.foo}}
{{$root.foo}}
But consider using Vuex for sharing data in your application - https://github.com/vuejs/vuex
Or pass that foo as a parameter to the route -https://router.vuejs.org/en/essentials/passing-props.html
Ofc it does not work. you have to set the data on the template you use.
in your case:
const Foo = {
template: '<div>{{foo}}</div>',
data () {
return {
foo: 'magic'
}
}
}
Cheers and happy coding.

Vue.js dynamic add and remove

I'm learning Vue.js for my game and I was wondering if there is a way to dynamically add and remove components in Vue.js ?
Here's my current code
var vue = new Vue({
el: "#fui",
template: ``
})
const HelloCtor = Vue.extend({
props: ['text'],
template: '<div class="hello">{{ text }}</div>',
});
const vm = new HelloCtor({
data: {
text: 'HI :)'
}
});
/*
How can I do something like this?
vue.add(vm);
vue.remove(vm);
*/
The code basically speaks for himself
So, is it possible (and how?) to dynamically add and remove Vue.js components to a Vue?
You need a place to put vm in the template. Then you can $mount the component manually to an element with vm.$mount('el'). You can also delete the element with vm.$destroy(true). Destroy won't delete the element from the DOM. You'll need to do that manually with something like (vm.$el).remove()
I'm not 100% this is what you're looking for, and when you find yourself manually calling $destroy() you are probably not doing things right…but it does let you take control of the creating and destruction of components.
Something like this will let you create then destroy your component (note in this case once you destroy vm it's gone):
<div id="fui">
<button #click="make">Make</button>
<button #click="bye">destroy</button>
<div id="mountme"></div>
</div>
<script>
const HelloCtor = Vue.extend({
props: ['text'],
template: '<div class="hello">This has been {{ text }}</div>',
})
const vm = new HelloCtor ({
data: {
text: "Mounted"
}
})
var vue = new Vue({
el: "#fui",
template: ``,
methods: {
make: () => {
vm.$mount('#mountme')
},
bye: () => {
vm.$destroy(true);
(vm.$el).remove();}
}
})
</script>

Can't access root data in VueJS

It's my first post on stackoverflow, so sorry in advance if I do something incorrectly. My question;
I've setup a VueJS project, and I'm trying to reach data that I put in the App.vue from another component. To do this, I use this.$root.count for example, but it returns undefined.
Main.js:
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App'
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'history',
routes: [{
path: '/',
name: 'home',
component: function (resolve) {
require(['./components/Hello.vue'], resolve)
}
}, {
path: '/race-pilot',
name: 'racePilot',
component: function (resolve) {
require(['./components/RacePilot.vue'], resolve)
}
}
});
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
});
App.vue:
<template>
<div>
<div class="menu" ref="menu">
<router-link :to="{ name: 'home' }">Home</router-link>
<router-link :to="{ name: 'racePilot' }">Race Pilot</router-link>
</div>
<div id="app">
<router-view></router-view>
</div>
</div>
</template>
<style src="./assets/css/app.scss" lang="scss"></style>
<script>
import Hello from './components/Hello'
export default {
name: 'app',
components: {
Hello
},
data () {
return {
count: '0'
}
}
}
</script>
RacePilot.vue:
<template>
<div class="race-pilot">
</div>
</template>
<script>
export default {
name: 'RacePilot',
mounted() {
console.log(this.$root.count);
}
}
</script>
So the last log returns undefined. However, if I log this.$root, I do get the object. Anybody any idea? Thanks in advance!
Vuex is fine and all, but if you just want to expose a property to all of your views in a router based app, you can set it on the router-view.
<router-view :count="count"></router-view>
Then your view component just needs to accept it as a prop.
export default {
props:["count"],
name: 'RacePilot',
mounted() {
console.log(this.count);
}
}
this.$root references the top level Vue instance (new Vue...) and not the App VueComponent.
it is really hacky, other solutions are preferable, but this could work:
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App },
methods: {
getCount() {
return this.$children[0].count
}
},
});
and using getCount() in RacePilot.vue:
export default {
name: 'RacePilot',
mounted() {
console.log(this.$root.getCount());
}
}
You are trying to access data which is stored in App.vue but this data will be local to the component and not accessible globally.
App.vue is not the root instance (referred to by $root), instead it is the first component within the root instance which is actually created at main.js. It is during this creation time, you need to pass the data which will then be exposed for all child components via $root.
Here is the relevant portion of main.js, modified accordingly :-
new Vue({
el: '#app',
data: { count: 0 },
router,
template: '<App/>',
components: { App }
});
Tip : To confirm that App.vue is indeed the first child of root instance, try comparing the references of this.$root with this.$parent. It should returntrue which means that root instance is the parent of App.vue.
References :-
https://v2.vuejs.org/v2/guide/instance.html
https://v2.vuejs.org/v2/api/#vm-root
https://v2.vuejs.org/v2/guide/components-edge-cases.html#Accessing-the-Root-Instance
It should had worked as it is, as it is working here.
However a better way to manage global variables, which are available across components should be solved by state machine. Vue has Vuex for that purpose as stated here.
You should not do it like that.
Definitely you should not try to access other components like that.
To share data between components you can either use props (one-way binding) or Vuex to make data accessible and editable from all components through store.
You can use global $store or $router if you will start your Vue app this way:
new Vue({
el: '#q-app',
router,
store
render: h => h(require('./App'))
})
Then you can access store (for state change or access state (do not mutate state this way)) - this.$store.state.yourStaneName
You can also make the App component the actual root by passing the component directly to the Vue instance, which would look something like this:
new Vue(App).$mount('#app')
You'll probably have to move the router to App.vue, but this will make sure that this.$root will resolve to your App component directly.

Vue $route is not defined

I'm learning Vue router. And I want to made programmatic navigation without using <router-link> in templates file.
My router and view:
router = new VueRouter({
routes: [
{path : '/videos', name: 'allVideos', component: Videos },
{path : '/videos/:id/edit', name: 'editVideo', component: VideoEdit },
]
});
new Vue({
el: "#app",
router,
created: function(){
if(!localStorage.hasOwnProperty('auth_token')) {
window.location.replace('/account/login');
}
router.push({ name: 'allVideos' })
}
})
So by default I push to 'allVideos' route and inside that component I have a button and method for redirecting to ''editVideo'
button:
<button class="btn btn-sm btn-warning" #click="editVideo(video)">Edit</button>
method:
editVideo(video) {router.push({ name: 'editVideo', params: { id: video.id } })},
It works fine. But when I try to get id inside a VideoEdit component using $route.params.id I got error Uncaught ReferenceError: $route is not defined
Maybe it's because I'm not using npm for now just a cdn version of Vue and Vuerouter. Any solutions? Thanks!
Updated: btw in Vue dev tool I see $route instance inside the component
Updated:
var VideoEdit = Vue.component('VideoEdit', {
template: ` <div class="panel-heading">
<h3 class="panel-title">Edit {{vieo.name}}</h3>
</div>`,
data() {
return {
error: '',
video: {},
}
},
created: function () {
console.log($route.params.id);
},
})
Thanks to Sandeep Rajoria
we found solution, need to use this.$route except $route inside a component
For those who getting the error after adding this
TypeError: Cannot read property '$route' of undefined
We need to use a regular function instead of ES6 arrow functions
data: function() {
return {
usertype: this.$route.params.type
};
},
This worked for me.
import Vue from 'vue'
import Router from 'vue-router';
Vue.use(Router)
const router = new VueRouter({
routes: [
{path : '/videos', name: 'allVideos', component: Videos },
{path : '/videos/:id/edit', name: 'editVideo', component: VideoEdit },
]
});
new Vue({
el: "#app",
router,
created: function(){
if(!localStorage.hasOwnProperty('auth_token')) {
window.location.replace('/account/login');
}
this.$router.push({ name: 'allVideos' });
}
})
If you're using vue v2 & vue-router v2 then in vue-cli generated boilerplate way to access router e.g. from component is to import router (exported in router/index.js)
<script>
import Router from '../router';
then in your code you can use router functions like:
Router.push('/contacts'); // go to contacts page
For those attempting to use es6 arrow functions, another alternative to #Kishan Vaghela is:
methods: {
gotoRegister() {
this.$router.push('register')
}
}
as explained in the first answer of Methods in ES6 objects: using arrow functions
In my case these previous solutions don't work for me so
i did the following
<script>
import Router from '../router';
then in your code you can use this one
this.$router.push('/contacts');

Categories