Using #vue/server-renderer (vuejs 3) how do you get the CSS? - vue.js

I have been able to set up Server side rendering with Vuejs 3 using the code below but the renderToString method doesn't include the CSS and I also need to get the CSS rendered by the components.
example
const { renderToString } = require('#vue/server-renderer')
const createApp = require('./server/app').default
module.exports = async function (settings) {
const { app, router } = createApp(settings);
if (settings && settings.url) {
router.push(settings.url);
await router.isReady()
}
const html = await renderToString(app);
var toRet = { html: html, css: 'Still Need to get' };
return toRet;
};
The Single File Components so far are just boilerplate code specifying the CSS as scoped (shown below) but I'm also debating using CSS modules. I need the CSS in the Javascript file and not loaded separately as the site will be ran both in a Client Side manner with no Server Rendering and a Server Rendering manner.
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>

Related

How do I create a global component without injection?

There is a case that we need a component in global to use it like this.$toast('some words') or this.$dialog({title:'title words',contentText:'some words').
In Vue 2.x, we can add Toast.vue's methods to Vue.prototype, and call Toast.vue's methods everywhere. But how do we do this in Vue 3.x?
I read the document of i18n plugin demo in vue-next. But it needs to inject the i18n plugin into every component that needs to use it. It's not convenient.
A way showing the component anywhere in vue3 app without injection
mechanism
mountting the component into dom each time.
implementation
use 'Toast' for example:
step 1: create a SFC (Toast.vue)
<template>
<transition name="fade">
<div class="toast" v-html="msg" :style="style" #click="closeHandle"></div>
</transition>
</template>
<script>
import {ref,computed,onMounted,onUnmounted} from 'vue'
export default {
name: "Toast",
props:{
msg:{type:String,required:true},
backgroundColor:{type:String},
color:{type:String},
// closing the Toast when timed out. 0:not closed until to call this.$closeToast()
timeout:{type:Number,default:2000, validate:function (val){return val >= 0}},
// closing the Toast immediately by click it, not wait the timed out.
clickToClose:{type:Boolean, default: true},
// a function provied by ToastPlugin.js, to unmout the toast.
close:{type:Function,required: true}
},
setup(props){
let innerTimeout = ref();
const style = computed(
()=>{return{backgroundColor:props.backgroundColor ? props.backgroundColor : '#696969', color:props.color ? props.color : '#FFFFFF'}}
);
onMounted(()=>{
toClearTimeout();
if(props.timeout > 0)
innerTimeout.value = setTimeout(()=>{ props.close(); },props.timeout);
});
/**
* when toast be unmounted, clear the 'innerTimeout'
*/
onUnmounted(()=>{toClearTimeout()})
/**
* unmount the toast
*/
const closeHandle = () => {
if(props.clickToClose)
props.close();
}
/**
* to clear the 'innerTimeout' if it exists.
*/
const toClearTimeout = ()=>{
if(innerTimeout.value){
try{
clearTimeout(innerTimeout.value);
}catch (e){
console.error(e);
}
}
}
return {style,closeHandle};
},
}
</script>
<style scoped>
.toast{position: fixed; top: 50%; left: 50%; padding: .3rem .8rem .3rem .8rem; transform: translate(-50%,-50%); z-index: 99999;
border-radius: 2px; text-align: center; font-size: .8rem; letter-spacing: .1rem;}
.fade-enter-active{transition: opacity .1s;}
.fade-leave-active {transition: opacity .3s;}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {opacity: 0;}
</style>
step 2: create a plugin (ToastPlugin.js)
import Toast from "./Toast.vue";
import {createApp} from 'vue'
const install = (app) => {
// dom container for mount the Toast.vue
let container;
// like 'app' just for Toast.vue
let toastApp;
// 'props' that Toast.vue required.
const baseProps = {
// define a function to close(unmount) the toast used for
// case 1: in Toast.vue "click toast appeared and close it"
// case 2: call 'this.$closeToast()' to close the toast in anywhere outside Toast.vue
close:()=> {
if (toastApp)
toastApp.unmount(container);
container = document.querySelector('#ToastPlug');
if(container)
document.body.removeChild(container);
}
};
// show Toast
const toast = (msg)=>{
if(typeof msg === 'string')
msg = {msg};
const props = {...baseProps,...msg}
console.log('props:',JSON.stringify(props));
// assume the toast(previous) was not closed, and try to close it.
props.close();
// create a dom container and mount th Toast.vue
container = document.createElement('div');
container.setAttribute('id','ToastPlug');
document.body.appendChild(container);
toastApp = createApp(Toast, props);
toastApp.mount(container);
}
// set 'toast()' and 'close()' globally
app.config.globalProperties.$toast = toast;
app.config.globalProperties.$closeToast = baseProps.close;
}
export default install;
step 3: usage
in main.js
import ToastPlugin from 'xxx/ToastPlugin'
import { createApp } from 'vue'
const app = createApp({})
app.use(ToastPlugin)
// then the toast can be used in anywhere like this:
this.$toast('some words')
this.$toast({msg:'some words',timeout:3000})
Vue 3 provides an API for attaching global properties:
import { createApp } from 'vue'
const app = createApp({})
app.config.globalProperties.$toast = () => { /*...*/ }

How to disable Vuetify's style?

I want to parse markdown to html and use syntax highlighting.
My SFC is as follows:
<template>
<div v-html="html"></div>
</template>
<script>
import marked from 'marked'
import hljs from 'highlightjs';
export default {
name:"Article",
props:['md'],
computed:{
html(){
return marked(this.md)
}
},
created: function () {
marked.setOptions({
langPrefix: '',
highlight: function(code, lang) {
return hljs.highlightAuto(code, [lang]).value
}
})
},
}
</script>
<style src='highlightjs/styles/github-gist.css'></style>
The resulting code blocks are look like this:
This is Vuetify's style.
https://vuetifyjs.com/en/styles/content/#code
I want to disable or override it.
The following code does not work for code blocks:
<style scoped>
.v-application code {
background-color: unset !important;
color: unset !important;
box-shadow: unset !important;
}
.myclass {
color:red !important;
}
</style>
Result:
Vuetify has the following CSS specified for the code tags:
.v-application code {
background-color: #f5f5f5;
color: #bd4147;
box-shadow: 0 2px 1px -1px rgba(0,0,0,.2),
0 1px 1px 0 rgba(0,0,0,.14),
0 1px 3px 0 rgba(0,0,0,.12);
}
You can see this if you open developer tools and inspect a code tag on their website.
Either override those values to your own, or just set them all to unset or unset !important. For example:
.v-application code {
all: unset;
color: #eee
}
/* Or with increased specificity */
.v-application code.code--custom {
all: unset;
color: #eee
}
Actualy the style override you suffer from wouldn't be a problem if you just import your HighlightJS CSS directly after Vuetify in your main.js.
//main.js
import Vue from 'vue'
import App from './App.vue'
import vuetify from './plugins/vuetify';
import '<your_path>/highlight.min.css'
Consider also using a Vue Directive for global usage.
//main.js
Vue.directive('highlightjs', {
deep: true,
bind: function(el, binding) {
// highlight all targets
let targets = el.querySelectorAll('code')
targets.forEach((target) => {
// override this in case of binding
if (binding.value) {
target.textContent = binding.value
}
hljs.highlightBlock(target)
})
},
})
Then you can simply use it like this:
<pre v-highlightjs>
<code class="javascript">
// your code goes here //
</code>
</pre>
I made a JSFIDDLE for this, which is a modified version of a vue HighlightJS example by Chris Hager.
https://jsfiddle.net/b8jontzr/2/

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)
})
},

Check if everything (including video) is loaded in Vue?

I have a Vue project that is getting a little large due to an embedded html5 video and am wondering how to tackle the loading issue for this site.
Is there a way to know if everything is loaded in Vue so I can show a loading screen before everything is ready? And does this loading take into account of assets loading like images, videos, etc?
If you want to wait for the rest of the webpage to finish loading before displaying the video, you can wait until the window has loaded (load event) and then display the video via v-if.
Here's some additional things to consider (you're using webpack, right?):
Code splitting
If your JS bundle is getting too big, you can split it into smaller chunks and the webpack runtime will download the chunks asynchronously on demand.
I like to split my vendor code into a separate chunk, as well as split off some router components like this:
{
path: 'foo',
component: () => import('./components/foo.vue'),
}
See Code Splitting (Webpack docs) and Async Components (Vue docs) for more info.
Loading page
Your webpage will initially appear blank while the browser is downloading the HTML and JS assets before the Vue app has been bootstrapped. During this time, you can display whatever plain HTML content you want, then mount the root Vue component over the loading HTML.
const App = {
template: '<div>My App</div>',
};
function bootstrap() {
new Vue({
el: '#app',
render: h => h(App),
});
}
// Simulate loading
setTimeout(bootstrap, 2000);
body {
font-family: sans-serif;
}
#keyframes loading-anim {
from { opacity: 1; }
to { opacity: 0.3; }
}
.loading {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
font-size: 40px;
color: #888;
letter-spacing: -0.05em;
font-weight: bold;
animation: loading-anim 1s ease-in-out alternate infinite;
}
<div id="app">
<!-- Put whatever loading HTML content here -->
<div class="loading">LOADING</div>
</div>
<script src="https://rawgit.com/vuejs/vue/dev/dist/vue.js"></script>