Difference between revisions of "VueJS"
m (→See also) |
m (→See also) |
||
Line 182: | Line 182: | ||
*[http://router.vuejs.org/en/essentials/getting-started.html The Vue router] | *[http://router.vuejs.org/en/essentials/getting-started.html The Vue router] | ||
*[https://v1.vuejs.org/guide/application.html Building large-scale apps] | *[https://v1.vuejs.org/guide/application.html Building large-scale apps] | ||
− | *[https://github.com/MetinSeylan/Vue-Socket.io?ref=madewithvuejs Vue-Socket.io] ''- and [https://medium.com/@michaelmangial1/getting-started-with-vue-js-socket-io-8d385ffb9782 this]'' | + | *[https://github.com/MetinSeylan/Vue-Socket.io?ref=madewithvuejs Vue-Socket.io] ''- and [https://medium.com/@michaelmangial1/getting-started-with-vue-js-socket-io-8d385ffb9782 this tutorial]'' |
[[Category:JavaScript]] | [[Category:JavaScript]] |
Revision as of 20:54, 11 June 2017
It's becoming more and more critical in recent months that I get up to speed with a decent JavaScript framework that supports Single Page Applications. I've built a few simple SPA's before one without a framework, and the others using Backbone. Backbone is getting a bit dated now, and I need to build an SPA that is considerably more complicated than those I've made before.
After a lot of looking around I've settled on the Vue2 framework which is similar to React but has a simpler learning curve (it's practically as simple as jQuery to get started with by just including the script and writing code, or the next step, building with the simple template) while also scaling very well - in fact in virtually all tests it's shown to be faster and more scalable than React. Another popular option is AngularJS which shares a lot of similarities with Vue - both React and Angular have served as strong inspiration for the development of Vue. As is the case for React, Angular has a steep learning curve which is one of the main reasons for me to prefer Vue - I like the idea of an efficient minimalist system that is very easy to get started with and yet also very scalable. Angular is also very "opinionated" which means that it dictates a lot about the way you should structure you're application. Vue is much more flexible, but also offers the Webpack template if you want an entire tool-chain and structure predefined for you. Angular2 is much more efficient, but Vue still beats it, and in terms of size, Vue's 23KB is hard to beat (actually it is beatable though - RiotJS is only 10KB, but I feel that the massive efficiency gains of Vue are worth the extra few KB).
Contents
General
The general idea behind Vue is to "vueify" elements by constructing a new Vue instance with the el property selecting the node(s), which similar to jQuery's $("#foo") concept.
new Vue({
el: "#foo"
});
This is not a very useful example though, the most simple functional "Hello World!" example is:
<div id="foo">{{bar}}</div>
var app = new Vue({
el: "#foo"
data: {
bar: "Hello World!"
}
});
Here the element that the Vue instance binds to has a mustache-style template parameter specified in it called bar. The Vue instance binds to it with the #foo selector in its el property, and creates a persistent connection between the bar parameter in the element and the bar sub-property of its data property. The bar property of the view instance can be accessed or changed via the instance with app.bar and any updates to it will be immediately reflected in the HTML element.
Component model
Vue components allow this idea to be encapsulated into a re-usable package, the usual usage being to register the component with a custom element as follows:
<div id="baz">
<foo></foo>
</div>
// Register the component with "foo" custom-elements
Vue.component('foo', {
template: '<div>This is the Foo component!</div>'
})
// Instantiate the component by "vueifying" the element containing the custom-element
new Vue({
el: '#baz'
})
A component is actually a sub-class of the Vue object created by internally calling the Vue.extend method which adds all the passed options to the base Vue class and returns a callable constructor function reference that's used to create new instances of the component via the new directive. Components can be further sub-classed by calling their extend method in the same way.
The Vue.component method is then used to register a component with a custom element as follows. For comvenience, the Vue.component method allows these two separate steps to be combined into one by providing the options object along with the custom-element name which is what was done in the above example.
// Create the new component as an extension of the base Vue class
var newComponent = Vue.extend({
template: '<div>This is the Foo component!</div>'
})
// Register the component with "foo" custom-elements
Vue.component('foo', newComponent);
The VueRouter extension
The Vue Router is used for making Single Page Applications. A VueRouter instance is created containing a map of all the paths and sub-paths for the application structure and which components they link to. It provides a method for creating links that will activate a path change and provides events for performing various actions in response to these changes such as transitions.
The components that are mapped to in the routes can be either be an actual component constructor created via Vue.extend(), or just a component options object. The association of the components with custom elements is not necessary since in this context they're always applied to <router-view> custom-elements, and the instantiation of them onto the DOM is handled automatically by the router mechanism. This is the reason that Vue.extend or even just an options object is all that is needed for the router components.
If the component needs to be used or referred to elsewhere in the application then Vue.extend is needed, otherwise simply passing the options object is all that's necessary and the router will take care of all the registration and instantiation internally.
Merging state
Vue comes with the Vue.set, Vue.add and Vue.delete methods which allow objects to be updated such that any watchers will be triggered and also the setting of items deep within structures doesn't interfere with watchers at higher levels by overwriting the containers that are referred to be other watchers.
However there is a problem that I was not able to find any solution to involving watching lists. Perhaps I should really be using Vuex for my state management which might somehow overcome this issue, but in the meantime I've come up with a solution that works for the native Vue system.
The problem is that when an item in a list changes, any watch methods that are called are passed the entire list in the changed-item parameter even if only a single item was changed. The entire list must be processed to either rebuild/update all the items or figure out which ones have changed and need updating.
To get around this I made the following recursive merge function which allows single items or entire structures to be merged into the application state preserving all existing references and thus leaving all watchers intact. By working recursively the function can keep track of the keys whenever various parts of the state are changed, it stores these keys in a queue parameter in the state so that the next time a watch function is activated it has access to all the keys that have been updated since the last watch call, or since the merge was started.
state.merge = function(o) {
// Traverse the o structure passing a path array and val to a sub-function
function t(o, p, f) {
for(var i in o) {
var q = p.concat(i);
f(q, o[i]);
if(o[i] !== null && typeof(o[i]) === 'object') t(o[i], q, f);
}
}
// Create any path elements from o that don't already exist in state
// - v will either a value to be added (leaf node) or a container (path element)
// - array type objects are considered to be values not containers
t(o, [], function(p, v) {
var i,c = (typeof v === 'object') && !$.isArray(v);
var k = c ? false : p.pop();
if($.isNumeric(k)) return;
var r = state;
for(i in p) {
i = p[i];
if($.isNumeric(i)) return;
if(!(i in r)) Vue.set(r, i, {});
r = r[i];
}
// If the value is not a container, set it in the state structure
if(!c) {
// If it's an array, don't merge null values into the state
if($.isArray(v) && $.isArray(r[k])) {
for(i in v) if(v[i] === null && i in r[k]) v[i] = r[k][i];
}
// Make the path available to any watchers and set the value in the state
p = p.join('.');
if(!(p in state.queue)) state.queue[p] = [];
state.queue[p].push(k);
Vue.set(r, k, v);
}
});
};
Now you can merge compatible structures that arrive from the server, or update single items as long as they're in a mergeable form containing the whole object path. Null values can be used to leave some values in the state unchanged, for example here I'm updated a single location's title and position, but leaving other values unchanged.
state.merge({
locations: {
'50c4f5': [-36.825, 174.807, "2 Foo Avenue, Barville, Santa Baza", null, null, null]
}
});
A typical watch function may look something like the following example. Here map markers are updated whenever items in a locations list are changed (but it's not called for every change in a merge call, usually just once at the end of the whole merge). Rather than perform updates based on the new and old values that are available as parameters to the function, we call our update function by popping items off the queue. The queued changes are separated into keys named by their dot-separated path into he state structure so that different data merges can occur simultaneously without interfering with each others queues.
watch: {
'state.locations': {
handler: function() {
var id;
while(id = app.locations.queue.pop()) { updateMarker(id); }
},
deep: true
}
}
Vue-cli and Web-pack
Vue-cli is a simple CLI for scaffolding Vue.js projects from the shell using simple official or custom project templates to rapidly build working prototypes. Vue-loader (a Webpack loader for Vue) is used to convert the single-file-component syntax into a plain JavaScript module for normal execution in the browser.
The init command creates a new project from a template, and the build command rebuilds it after changes are made.
First NodeJS and the Node package manager must be installed:
apt install nodejs npm
Nodejs must then be brought up to date using their own upgrade system since the operating system package managers are usually well behind what's required by most dependencies.
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
sudo ln -sf /usr/local/n/versions/node/<VERSION>/bin/node /usr/bin/node
sudo ln -sf /usr/local/n/versions/node/<VERSION>/bin/node /usr/bin/nodejs
Now vue-cli can be installed:
npm install -g vue-cli
And then a project created and run, for example:
cd /var/www
vue init webpack-simple my-project
cd my-project
npm install
npm run dev.
Notes
- It may be good to use Weex templates for cross-platform native rendering
- "Vue has a clearer separation between directives and components. Directives are meant to encapsulate DOM manipulations only, while components are self-contained units that have their own view and data logic. In Angular, there’s a lot of confusion between the two.
- Cleaning up on transitions
- Properties in routes
See also
- Awesome Vue - big list of examples and tutorials
- VueComponents.com - a lot of nice clear examples
- The Vue router
- Building large-scale apps
- Vue-Socket.io - and this tutorial