Router issue with m.route.link - mithril.js

While playing around with Mithril I stumbled upon this issue and I'm not sure if it's a bug or a feature or I'm doing something wrong.
Please, run the script below and click on View Two and then on Link three. You'll see that the console outputs "RENDER TWO" each time you click on Link three. It doesn't make any sense, because in the code link component has neither href nor oncreate: m.route.link specified. It's as if it inherits it from the previous route or something. Also, if I remove onclick handler everything works as expected(console outputs nothing).
I've also opened an issue on github. If you feel you can help fix it please go here.
Anyway, do you have any idea what's going on?
const outlet = document.body;
//COMPONENTS
class Link {
view(vnode){
return m('a', vnode.attrs, vnode.attrs.title);
}
}
class ViewOne {
view(vnode){
return m('div', 'view one');
}
}
class ViewTwo {
view(vnode){
return m('div', this.getLinkThree());
}
getLinkThree(){
return m(Link, {
title: 'Link three',
onclick: () => {} // removing this handler solves the problem (routerResolver's render not invoked)
});
}
}
//HELPERS
const getLinkOne = () => {
return m(Link, {
title: 'View One',
href: '/one',
oncreate: m.route.link
});
}
const getLinkTwo = () => {
return m(Link, {
title: 'View Two',
href: '/two',
oncreate: m.route.link
});
}
const getViewHolder = () => {
return m('#view-holder');
}
//INIT
m.render(outlet, [
getLinkOne(),
getLinkTwo(),
getViewHolder()
])
m.route(document.getElementById('view-holder'), "/one", {
"/one": {
render: () => {
console.log('RENDER ONE');
return m(ViewOne);
}
},
"/two": {
render: () => {
console.log('RENDER TWO'); //also logs when clicking on 'Link three'
return m(ViewTwo);
}
}
})
a {
padding: 5px;
background-color: grey;
margin-right: 5px;
}
#view-holder {
width: 200px;
height: 100px;
display: flex;
align-items: center;
justify-content: center;
background-color: lightgrey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/mithril/1.1.1/mithril.min.js"></script>

Eugene, this is expected Mithril 1.x behavior: triggering a ui-event handler causes a vdom build + diff.
Separately it's ... unusual ... to have both m.render() and m.route() calls as part of setup. In this case just m.route() suffices. Pls see here (you'll need to prefix the following short-link with "https://"): goo.gl/z8rZFf
BTW the above leads to an editor called "Flems" -- it encodes file references, in-situ code, etc into the URL, so to share a Flems just copy/paste its URL. This has the advantage of being able to share work without creating physical resources such as w/ JSBin, etc, but a downside is that in most cases the URL needs to be shortened to be share-able.

Related

Vue Unit Test Resize Screen and Update DOM

I have a component that displays an image if the screen is desktop and it hides the image if the screen is for mobile devices:
<script>
export default {
name: 'MyComponentApp',
}
</script>
<template>
<div class="my-component">
<div class="my-component__image-container">
<img class="my-component__image-container--img" />
</div>
</div>
</template>
<style lang="scss" scoped>
.my-component {
&__image-container {
overflow: hidden;
width: 50%;
&--img {
width: 100%;
height: 100%;
object-fit: cover;
}
}
}
#media (max-width: 600px) {
.my-component {
&__image-container {
&--img {
display: none;
}
}
}
}
</style>
When I try to do the unit test case and test if the image is hidden when the window.width is below 600px, it doesn't update the DOM and the image is still visible:
import MyComponentApp from './MyComponentApp.vue';
import { shallowMount } from '#vue/test-utils';
const factory = () => {
return shallowMount(MyComponentApp, {});
};
describe('DownloadApp.vue', () => {
let wrapper;
beforeEach(() => {
wrapper = factory();
});
describe('Check Items on Mobile Devices', () => {
it('Img on div.my-component__image-container shouldn\'t be displayed', async () => {
jest.spyOn(screen, 'height', 'get').mockReturnValue(500);
jest.spyOn(screen, 'width', 'get').mockReturnValue(500);
await wrapper.vm.$nextTick();
const image = wrapper.find('div.my-component__image-container > img');
expect(image.isVisible()).toBe(false);
});
});
});
However, the test fails:
DownloadApp.vue › Check Items on Mobile Devices › Img on div.my-component__image-container shouldn\'t be displayed
expect(received).toBe(expected) // Object.is equality
Expected: false
Received: true
Does anybody know how to update the DOM or make the test case realized that the screen width has changed and the image should be displayed?
CSS #media queries depend on the viewport size, which currently cannot be manipulated from Jest alone, and setting window.innerWidth in Jest won't have an effect in this case.
Alternatively, you could resize the viewport in Cypress tests. In a Vue CLI project, you could add the Cypress plugin by running this command from the root of your project:
vue add e2e-cypress
Then in <root>/tests/e2e/test.js, insert the following tests that use cy.viewport() to set the viewport size before checking the img element's visibility:
describe('My img component', () => {
it('should show image for wide viewport', () => {
cy.visit('/') // navigate to page where test component exists
cy.viewport(800, 600)
cy.get('.my-component__image-container--img').should('be.visible')
})
it('should hide image for narrow viewport', () => {
cy.visit('/') // navigate to page where test component exists
cy.viewport(500, 600)
cy.get('.my-component__image-container--img').should('not.be.visible')
})
})

Vue JS props is underfined

Im using Gridsome frame work for VUE JS
I am navigating to a new page by using this.$router.push(PATH, PARAMS)
this.$router.push({path: `/${value.sectionLink}/`, params: {pageOBJ: value}})
The page route works fine - however the PROP, pageOBJ is undefined in the page as seen in the VUE inspector:
it should be an object (which is what VALUE is set to) i.e.
I've tried a number of different techniques to resolve this but have not managed to figure this out so I assume I have missed something here?
gridsome auto generates the page routes when you add a new PAGE.VUE file to the /pages folder -
Is this the issue?
Gridsome also references graphQI, are you supposed to grab the data using graph and not by pushing Props?
Any help would be amazing here - please let me know if you need any further information.
Thanks -
W
UPDATE BASED ON CURRENT ANSWERS:
I have already added props:true to the component as shown below, but the issue is still present.
CODE SNIPPET - SUMMARY:
User clicks on the SectionTitle component, this then emits the page link
(each of the SectionTitle is a object from : sections array of Object)
To see the current online version of this please look at
wtwd.ninjashotgunbear.com
<template>
<Layout>
<div class="navs" v-for="section in sections" :key="section.sectionTitle">
<!-- On click delay for screen to come ove top -->
<!-- router to be put here -->
<SectionTitle :data="section" #routeChange="reRoute($event)"/>
</div>
<PageTransition :dataObj="transitionObj"/>
</Layout>
</template>
<script>
import SectionTitle from '#/components/SectionTitle.vue';
import PageTransition from '#/components/PageTransition.vue'
export default {
metaInfo: {
title: 'Hello, world!'
},
components: {
SectionTitle,
PageTransition
},
data(){
return {
// data to be passed to the components
sections: [
{
sectionTitle: 'Clients',
sectionLink: 'clients',
sectionSubTitle: '"Some of the amazing humans I have had the pleasure of working with"',
backgroundColor: '#F08080',
titleColor: '#E65454'
},
{
sectionTitle: 'Projects',
sectionLink: 'projects',
sectionSubTitle: '"I LIKE TO MAKE PROJECTS THAT WILL TEST MY KNOWEDGE AND EXPOSE MY WEAKNESSES"',
backgroundColor: '#20B2AA',
titleColor: '#11DACF'
},
{
sectionTitle: 'Skills',
sectionLink: 'skills',
sectionSubTitle: `"LEARNING WILL NEVER END, SO LONG AS YOUR AMBITIONS ARE STOKED, AND I've got plenty of ambition"`,
backgroundColor: '#A921B2',
titleColor: '#CA14D6'
},
{
sectionTitle: 'About Me',
sectionLink: 'aboutme',
sectionSubTitle: `"My joruney becoming a developer so far"`,
backgroundColor: '#FFFFFF',
titleColor: '#D1D1D1'
},
{
sectionTitle: 'Contact Me',
sectionLink: 'contactme',
sectionSubTitle: `"If you have any questions or want to reach out about a project then i'd love to speak with you"`,
backgroundColor: '#2185B2',
titleColor: '#0076AB'
}
],
divText: null,
transitionObj: null
}
},
methods:{
reRoute(value){
// 1)A) - change the text of the div to say the section it is being moved to
this.divText = value.sectionTitle
this.transitionObj = value
// FIND center pixcle value to place text - scrolled height + windowHeight / 2 = centerPos
let centerPos = window.scrollY+(window.innerHeight/2)
// Apply secific Title color - and center possitioning
document.querySelector('.leaveScreen p').style.cssText=`color: ${value.titleColor}; top: ${centerPos}px`
// 1) animate the loading screen
let screen = document.querySelector('.leaveScreen');
screen.style.cssText=`background: ${value.backgroundColor}; left: 0%`;
// 2) re-route the page
setTimeout(()=>{
this.$router.push({path: `/${value.sectionLink}/`, params: {pageOBJ: value}}) // << says that the route name is not found
// this.$router.push(value.sectionLink)
}, 700)
}
}
}
</script>
<style lang="scss">
// **** ERROR CAUSED BY NOT INSTALLING SCSS package ****
// https://gridsome.org/docs/assets-css/ &&&& npm install -D sass-loader node-sass
// Universal Font being used - LEMON MILK
#font-face {
font-family: LemonMilk;
src: url('../assets/fonts/LemonMilk.otf');
}
* {
box-sizing: border-box;
}
.navs {
font-family: LemonMilk;
}
.SectionTitle{
cursor: pointer;
}
</style>
Pass name rather than path in this.$router.push()
this.$router.push({name: ${value.sectionLink}, params: {pageOBJ: value}})
You should add props:true to the route definition :
{
path:'/thepath/:theParam',
component:SomeComponent,
props:true
}

Window.resize or document.resize which works & which doesn't? VueJS

I am using Vuetable and its awesome.
I am trying to create a top horizontal scroll, which I have done and its working fine. But I need to assign some events on the window.resize.
I created a component such as
<template>
<div class="top-scrollbar">
<div class="top-horizontal-scroll"></div>
</div>
</template>
<style scoped>
.top-scrollbar {
width: 100%;
height: 20px;
overflow-x: scroll;
overflow-y: hidden;
margin-left: 14px;
.top-horizontal-scroll {
height: 20px;
}
}
</style>
<script>
export default {
mounted() {
document.querySelector("div.top-scrollbar").addEventListener('scroll', this.handleScroll);
document.querySelector("div.vuetable-body-wrapper").addEventListener('scroll', this.tableScroll);
},
methods: {
handleScroll () {
document.querySelector("div.vuetable-body-wrapper").scrollLeft = document.querySelector("div.top-scrollbar").scrollLeft
},
tableScroll() {
document.querySelector("div.top-scrollbar").scrollLeft = document.querySelector("div.vuetable-body-wrapper").scrollLeft
}
}
}
</script>
I am calling it above the table such as <v-horizontal-scroll />
I created a mixin as
Vue.mixin({
methods: {
setScrollBar: () => {
let tableWidth = document.querySelector("table.vuetable").offsetWidth;
let tableWrapper = document.querySelector("div.vuetable-body-wrapper").offsetWidth;
document.querySelector("div.top-horizontal-scroll").style.width = tableWidth + "px";
document.querySelector("div.top-scrollbar").style.width = tableWrapper + "px"
}
}
})
And I am calling it when the user component on which Vuetable is being created
beforeUpdate() {
document.addEventListener("resize", this.setScrollBar());
},
mounted() {
this.$nextTick(function() {
window.addEventListener('resize', this.setScrollBar);
this.setScrollBar()
});
},
I want to understand how this resizing event working.
If I change even a single thing in the above code. I am starting to have issues.
Either it doesn't set the width of scroll main div correctly or even this.setScrollBar don't work on resizing.
I am not clear what is the logic behind this and how it is working?

print vueJS component or convert to pdf

I have a vueJS component that I want to print. However, when I use the standard print dialog I lose all the CSS and basically only have plain text.
I have also tried Printd.
My code is along the lines of:
mounted () {
this.cssText = `
.a4-paper {
height: 29cm;
width: 14cm;
}
h4, h3, h2, h1 {
text-align: center;
width: 100%;
}
label.underline {
border-bottom: solid black 1px;
height: 0.3cm;
width: 100%;
}`;
this.d = new Printd()
},
methods: {
show(event: Event) {
this.event = event;
this.visible = true;
},
print() {
this.d.print(this.$el, this.cssText)
}
}
However, the result looks nothing like how the component is rendered. I haven't been able to find a solution for this. Can somebody help me?
The problem exists because printd creates a new Document for printing, therefore styles aren't carried down into the child component, which you are referencing with this.$el
The workaround which I use is to take all of the style elements from the head of the current document and append them to the document that printd creates. Change your print method to the following;
print() {
const d = new Printd()
d.print(this.$el, this.cssText, (win, doc, node, launchPrint) => {
// Get style elements
const styles = [].slice.call(document.getElementsByTagName('style'))
// append them to the the new document head element
styles.forEach(styleElement => doc.head.appendChild(styleElement.cloneNode(true)))
launchPrint(win)
})
},

Sticky navigation which appears on scroll

I am trying to create a menu which is hidden but appears, fixed to the top, once the user begins scrolling down the page. So far I have managed to create a menu which sticks to the top upon scrolling but am stuck on how to hide this menu initially.
This is the code I am using so far:
(I am using wordpress-headway)
JQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
//STICKY NAV
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i) ? true : false;
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i) ? true : false;
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i) ? true : false;
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i) ? true : false;
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows());
}
};
//Calculate the height of <header>
//Use outerHeight() instead of height() if have padding
var aboveHeight = $('.top-row').outerHeight();
//when scroll
$(window).scroll(function(){
//if scrolled down more than the header’s height but this isn't mobile
if ($(window).scrollTop() > aboveHeight && !isMobile.any()){
// if yes, add “fixed” class to the <nav>
// add padding top to the #content
// (value is same as the height of the nav)
$('.block-type-navigation').addClass('fixed').css('top','0').next()
.css('padding-top','42px');
} else {
// when scroll up or less than aboveHeight,
// remove the “fixed” class, and the padding-top
$('.block-type-navigation').removeClass('fixed').next()
.css('padding-top','0');
}
});
});
</script>
CSS:
.fixed {
position:fixed !important;
left: 0;
text-align: center;
}
.fixed .block-content {
display: inline-block;
text-align: left;
width: 940px; /* This should be the width of your grid!!! */
float:none;
}
.fixed {
position:fixed !important;
left: 0;
text-align: center;
display: block !important;
}
It's driving me crazy so I'd appreciate ANY help!
Thank you!
If you don't want the nav to show unless the user has scrolled passed a certain point then couldn't it always be fixed just off the top of the screen:
.menu {
position:fixed;
top:-42px;
}
then shown or hidden by toggling a class
.menu.is-visible {
top:0;
}
using a scroll listener.
$win = $(window);
$win.on('scroll', function() {
$(".menu").toggleClass('is-visible', $win.scrollTop() > 42);
});
You could even add some CSS animation to the top property
.menu {
-webkit-transition: top 0.2s ease-in-out;
}
to get a cool transition.
Note: All this code is typed out right in here and not tested.
Note: You should definitely put a throttle on the scroll handler too.