Mixing Vue.js into existing SSR website? - javascript

Is it possible/viable to use Vue to create components that get instantiated onto custom tags rendered by e.g. a PHP application? Some kind of "custom elements light"?
It "works" if I mount the Vue instance onto the page root element, but - as far as I understand - Vue uses the whole page as a template in this case. And I imagine this could be a performance issue and cause trouble if other javascript code messes with the DOM.
The goal is to progressively replace legacy jQuery code. Is there an common approach for this problem?
Edit: Nesting these components is also a requirement. A simple example would be nested collapsibles.
Edit 2: Some fiddles to illustrate the problem.
A working solution based on riot.js:
https://jsfiddle.net/36xju9sh/
<div id="page">
<!-- This is supposed to show "This is a test." twice. -->
<test>
<test></test>
</test>
</div>
<script type="riot/tag">
<test>
<p>This is a test.</p>
<yield/>
</test>
</script>
<script>riot.mount('*')</script>
Two approaches using Vue.js:
https://jsfiddle.net/89ejjjsy/1/
HTML:
<div id="page">
<!-- This is supposed to show "This is a test." twice. -->
<test>
<test></test>
</test>
</div>
<script type="text/x-template" id="test-template">
<p>This is a test.</p>
<slot></slot>
</script>
Javascript:
Vue.config.ignoreCustomElements = ['test'];
// This won't hit the nested <test> element.
new Vue({
el:'test',
template: '#test-template',
});
// This does, but takes over the whole page.
Vue.component('test', {
template: '#test-template',
});
new Vue({
el: '#page',
});

You do not have to use whole page as Vue instance scope. It is more than ok to for example, use #comments-container as scope for comments component which will be nested somewhere on your page.
You can have multiple VueJS instances on one page.

Related

Vue only renders first custom component issue

I have a simple Vue app where I'm trying to render multiple custom components, here's what I'm trying:
JS
Vue.component('refinement-list', {
props: ['attribute', 'title'],
template: '<div>{{attribute}} - {{title}}</div>'
});
new Vue({
el: '#app'
});
HTML
<div id="app">
<refinement-list attribute="test" title="Test" />
<refinement-list attribute="sample" title="Sample" />
</div>
However the problem is that only the first component is rendered, see working example:
https://codepen.io/javiervd/pen/vYBpQMm
I tried registering the component locally instead but no luck. I'm also using Vue with a script tag in my app because I can't use a build system for this particular project, not sure if that matters.
Can anyone point me in the right direction? Thanks.
Since you are defining the template in the DOM, you can't use self-closing tags for the custom components.
This should work:
<div id="app">
<refinement-list attribute="test" title="Test"></refinement-list>
<refinement-list attribute="sample" title="Sample"></refinement-list>
</div>
This limitation doesn't exist in template strings or Single File Components.
You can read more about this here: https://v2.vuejs.org/v2/style-guide/#Self-closing-components-strongly-recommended
You should give like this in the HTML section if you want to use the self-closing tags. But it's not recommended for DOM Templates
<div id="app">
<div>
<refinement-list attribute="test" title="Test1" />
</div>
<div>
<refinement-list attribute="test" title="Test2" />
</div>
</div>
I forked your codepen and can confirm this is working with the separate closing tag style, in place of using self-closing tags for the components.
<div id="app">
<refinement-list attribute="test" title="Test"></refinement-list>
<refinement-list attribute="sample" title="Sample"></refinement-list>
</div>
ref: https://codepen.io/edm00se/pen/pozpqym?editors=1010
The self-closing tag versus (full?) closing tag is discussed in the vue style guide page (v2) and it is expressed that for string templates (as I suspect codepen is doing when loading your HTML content), to use the closing tag, while self-closing are fine in single-file components, JSX, and string templates (things which are processed during build and component names are better known).

Vuejs and drupal

I'm working on a Drupal project where we compile the js and sass of the theme with webpack. As we are moving in a near future to other backend(Laravel), and the idea is to use vuejs on front-end. So it seems to us a good idea, in meanwhile, start using vuejs in some pages and components, so we could start learn it about it. I have experience with angular and react but none with vue. I add it vue, the vue-loader, etc, but seems dificult to make it work and I'm not sure which could be the best way to implement/add vuejs in this escenario. Any recomendation or link will we very helpful.
Introduction
Vue is good choice because of two reasons in your case:
It is simplest to learn than Angular and React
It is progressive - it means you can easy use it only in constrained part of your existing project.
If you look at dock of life cycle of Vue instance
https://v2.vuejs.org/v2/guide/instance.html
You will see there are some options of create template and connect it with instance of vue.
a) by "el" option - selecting existing element from dom
b) by template option
including template as a string
selecting template by id of script with type text/x-template
You can use Vue instantly after page load or mount it later so you have flexibility.
Examples
I understood your question is about simplest way to integrate vue with drupal. I think that these examples of use Vue on simple html page will help you.
Simplest way
Simplest way is use el option and load Vue from cdn. ( remember about change cdn to minified on production )
<style>
[v-cloak] {
display: none;
}
</style>
<div id="app" v-cloak>
<h1>{{ heading }}</h1>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<script>
new Vue({
el: "#app",
data: { heading: "Hello World" }
});
</script>
By using text/x-template
<div id="app"></div>
<script id="app-template" type="text/x-template">
<div>
<h1>{{heading}}</h1>
</div>
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<script>
let v = new Vue({
template: `#app-template`,
data: { heading: "Hello World" }
});
v.$mount();
document.querySelector("#app").appendChild(v.$el);
</script>

Angular 1 how to properly include external component inside ng-include?

Situation: I have a view where I'm including a fragment with ng-include. The fragment loads perfectly and works as expected when inside view where controller is defined.
My problem is, that when I want to include external component inside the "ng-include" fragment "myView.html", it doesn't show up. When including it inside the main view where the controller is, it shows up and works as expected.
Main view:
<div ng-controller="MyController">
<div data-ng-include src="'views/myView.html'"></div>
<!-- When loaded here, the component shows up -->
<!-- <div id="componentDiv"></div> -->
</div>
Fragment "myView.html":
<div>
<div id="componentDiv"></div>
</div>
The component is loaded inside the "MyController", where "componentDiv" is the "id" of "div" where the component is placed:
var testObj = new TestObj({"container": "componentDiv"});
Trying to do this to be able to use this fragment with full functionality in several places.
Any ideas or suggestions what to look up or try?
IMHO I think that by saying "...to be able to use this fragment with full functionality in several places" you just answered your question. What you need is to build a custom directive and use it in any place you like.
see directive samples e.g. Angular documentation on directives

How to insert and nest a component within another in ractive.js when the components are in two separate files?

I've been learning ractive.js for few weeks and I am trying to build a feature within a larger webpage that lists out three items. Each list has it's own title and description. Each list is a component (the list-component) with its own styles and javascript (each component is a separate html). I also have a component (description-component) that is responsible for writing out the title and description and it is in a separate html file. The problem I am having is 'importing' or bringing in that description-component into the list-component so the output in the main index html file is this:
<description title="Name">
<list-items/>
</description>
So far I looked into the yield directive and tried some examples but that was a simple example using two components on the same document. I am not sure if that is the correct way. This is what is in the description-component html file:
<p>{{title}}</p>
I tried using ractive-load.js and load up the description-component html for every list-component file like in this example on their github:
Ractive.load({
Foo: 'my-components/foo.html',
Bar: 'my-components/bar.html'
}).then( function ( components ) {
var foo = new components.Foo({
el: 'body',
data: { ... }
});
var bar = new components.Bar({
el: 'body',
data: { ... }
});
}).catch( handleError );
and that seemed like an overkill and thought there must be a better way. How would I go about approaching this?
The loading of Ractive components is not directly related to handling nested components and passing yielded content to components.
Ractive.load works by fetching one or more html files that it then resolves to Components. From your code samples, it seems you've got that part working. For larger apps, I usually use a build tool plugin to pre-bundle all my Ractive components so they're deliverable in one file or even rolled into my main bundle js.
However the components are made available, they need to be registered on either the consuming component (or a view parent) or globally:
Ractive.load({
Foo: 'my-components/foo.html',
Bar: 'my-components/bar.html'
}).then( function ( components ) {
Ractive.components.foo = components.Foo;
Ractive.components.bar = components.Bar;
// now create your actual top-level view instance(s)
}).catch( handleError );
In component architectures, you create trees or bushes of components. I usually only have one top level app component, but it certainly is feasible to create multiple trees that start at different places in the DOM.
For simplicity, continuing on the above example, let's create a generic ractive instance that uses the two components Foo and Bar we registered (notice we use the property name we assigned to Ractive.components):
const ractive = new Ractive({
el: document.body,
sayHello() {
alert('hello from main Ractive instance');
},
template: `
<h1>my kewl app</h1>
<foo>
<h3 on-click="sayHello()">hello world</h3>
<bar bizz="{{buzz}}"></bar>
</foo>
`
});
In this case we're passing some content (html and our bar component) to the foo component by including it as the <foo> element content.
How this content is used depends on the foo template. There are two choices:
<div>
<h2>foo component template</h2>
{{>content}}
<p>some more stuff</p>
</div>
In this example, we're using the built-in partial "content" to tell the template to put provided content in the {{>content}} slot. In this case the provided content is passed like a partial, and any directives will be applied against the foo component. So in this example, clicking on the h3 header will try and run foo.sayHello(). And when passing the bizz data to the bar component, Ractive will start looking in the foo component for buzz.
Often, this isn't what you want. What you would rather have happen is for the parent to own the directives. So instead the foo template would look like:
<div>
<h2>foo component template</h2>
{{yield}}
<p>some more stuff</p>
</div>
And now when h3 is clicked, it calls the main ractive.sayHello() method as the content was passed to be rendered in the DOM by the the foo component, but it was still owned by the passing instance. Likewise Ractive will start look for buzz in the main instance, not foo.
With yield you can also name multiple partials to be passed:
<!-- "foo" template: -->
<div>
<header>{{yield header}}</header>
<section>
<div>something here</div>
<div>{{yield message}}</div>
</section>
</div>
<!-- using "foo": -->
<div>
<foo>
{{#partial header}}
<h2>This is the header to use</h2>
{{/partial}}
{{#partial message}}
<p>This is the message to use, with a bar component to boot</p>
<bar></bar>
{{/partial}}
</foo>
</div>

Routing in polymer 1.0

I am new to web development and building an application using polymer 1.0.4. I am using the page.js routing similar to the example in start kit. Now many of the custom element that I built are using ajax and periodically refresh the data. The problem with page.js routing that It seems it loads all custom elements even if the element is not viewed by user. so all custom elements are loading the data even if it is not needed. my questions:
1- How could I fix this so the the elements load data only when they are viewed by the end users? Should I change the routing to another options like more-routing?
2- if the user filled the data in one custom element , then clicked on link to another element. The data will remains when the user goes back to the first custom element? How could I reset the polymer and html elements in the custom element when the use back to an old view?
Again, I'd recommend https://github.com/PolymerLabs/more-routing Eventually a 'carbon' (if I recall the name correctly) set of components will deal with this, according to the polymer summit videos, but until then this seems the standard approach.
Set up the pages via:
<more-routing-config driver="hash"></more-routing-config>
<more-route name="one" path="/one"></more-route>
<more-route path="/two">
<more-route name="two" path="/:name"></more-route>
</more-route>
Then the menu via:
<more-route-selector>
<paper-menu selected="0">
<paper-item route="{{urlFor('one')}}">One</paper-item>
<paper-item route="{{urlFor('two', {name: 'sup'})}}">Two</paper-item>
</paper-menu>
</more-route-selector>
And then the actual pages via:
<more-route-selector selectedParams="{{params}}">
<iron-pages selected="0">
<section route="one">
<div> Page one </div>
</section>
<section route="two">
<div> Page two: {{params.name}} </div>
</section>
</iron-pages>
</more-route-selector>
I used it when it was under the Polymore repository on github, and the samples above are from such, but it doesn't seem to have changed that much in its new home.
After you've set up the basics, listen for changes on the iron-pages, such as events that are available here. In such listeners, you can load the data for each section in iron-pages. One approach would be to use such listeners to call a method of a custom element, perhaps using a behaviour, that then brings down the data.
Try dna-router. You can create define states and routes in HTML only.
Setup routes by:
<dna-new-state state='home' route='/home'></dna-new-state>
<dna-new-state state='user' route='/user/:id/'></dna-new-state>
Create views by:
<dna-view
state='home'
element='home-template'></dna-view>
You can get all params inside your home-template polymer properties.
var params = this.params
For a detailed documentation, visit : https://github.com/Saquib764/dna-router
Firstly, the PolymerLabs/more-routing library is a nice alternative to page.js and is quite easy to implement. As this library is more declarative you can do things like:
routes.html
<more-routing-config driver="hash"></more-routing-config>
<more-route name="myRoute" path="/my-route-path/:id"></more-route>
app-element.html
<dom-module id="app-element">
<style>
iron-selector > * {
display: none;
}
iron-selector > .iron-selected {
display: block;
}
</style>
<template>
<more-route-selector>
<iron-selector>
<x-element></x-element>
</iron-selector>
</more-route-selector>
</template>
<script>Polymer({ ... });</script>
</dom-module>
x-element.html
<dom-module id="x-element">
<template>
<more-route id="route" context name="myRoute" params="{{params}}" active="{{activeRoute}}"></more-route>
</template>
<script>
Polymer({
is: 'x-element',
observers: [ '_paramsChanged(activeRoute, params.id)' ],
_paramsChanged: function(activeRoute) {
if (activeRoute) {
// Active route
} else {
// Inactive route
}
}
})
</script>
</dom-module>
Check out the polyfora app in the demo folder of the repository.
Otherwise, to use page.js I would consider:
Remove any auto iron-ajax queries in custom elements;
Pass a state attribute to custom elements;
Add an observer to any state changes within each custom element which triggers a function to run any iron-ajax queries.
As of Polymer 1.4, carbon-route (later renamed app-route) can be used:
https://github.com/polymerelements/carbon-route
https://blog.polymer-project.org/announcements/2016/03/28/carbon-route-released/
https://www.polymer-project.org/1.0/articles/routing.html
Here's an example taken from the polymer blog:
<carbon-location route="{{route}}">
</carbon-location>
<carbon-route route="{{route}}" pattern="/tabs/:tabName" data="{{data}}">
</carbon-route>
<paper-tabs selected="{{data.tabName}}" attr-for-selected="key">
<paper-tab key="foo">Foo</paper-tab>
<paper-tab key="bar">Bar</paper-tab>
<paper-tab key="baz">Baz!</paper-tab>
</paper-tabs>
<neon-animated-pages selected="{{data.tabName}}"
attr-for-selected="key"
entry-animation="slide-from-left-animation"
exit-animation="slide-right-animation">
<neon-animatable key="foo">Foo Page Here</neon-animatable>
<neon-animatable key="bar">Bar Page Goes Here</neon-animatable>
<neon-animatable key="baz">Baz Page, the Best One of the Three</neon-animatable>
</neon-animated-pages>
See also similar question: Polymer 1.0 - routing

Categories

Resources