window is not defined Nuxt for vue-slick - vue.js

Hello I am having an issue with Nuxts ssr. I a trying to add 'vue-slick' to my web app and no matter what I do it continues to show "window is not defined".
As you can see I have tried multiple ways to allow vue-slick to be loaded on client side. Using plugins didn't help, using process.client in my component did not work as well.
Components/Carousel/Carousel.vue
<template>
<div class="carousel">
<Slick ref="slick" :options="slickOptions">
<a href="http://placehold.it/320x120">
<img src="http://placehold.it/320x120" alt="">
</a>
...
<a href="http://placehold.it/420x220">
<img src="http://placehold.it/420x220" alt="">
</a>
</Slick>
</div>
</template>
<script>
if (process.client) {
require('vue-slick')
}
import Slick from 'vue-slick'
export default {
components: {
Slick
},
data() {
return {
slickOptions: {
slidesToShow: 4
},
isMounted: false
}
},
methods: {
}
}
</script>
nuxt.config.js
plugins: [
{ src: '~/plugins/vue-slick', ssr: false }
],
plugins/vue-slick
import Vue from 'vue'
import VueSlick from 'vue-slick'
Vue.use(VueSlick);
Thanks for any help you can give!

So this is due to nuxt trying to render the slick component on the server side, even though you have set ssr: false in nuxt.config.
I have had this issue in other nuxt plugins and these steps should fix it.
in nuxt.config.js add this to your build object:
build: {
extend(config, ctx) {
if (ctx.isServer) {
config.externals = [
nodeExternals({
whitelist: [/^vue-slick/]
})
]
}
}
}
and in the page where you are trying to serve it you have to not mount the component until the page is fully mounted. So in your Components/Carousel/Carousel.vue set it up like this:
<template>
<div class="carousel">
<component
:is="slickComp"
ref="slick"
:options="slickOptions"
>
<a href="http://placehold.it/320x120">
<img src="http://placehold.it/320x120" alt="">
</a>
...
<a href="http://placehold.it/420x220">
<img src="http://placehold.it/420x220" alt="">
</a>
</component>
</div>
</template>
Then in your script section import your component and declare it like this:
<script>
export default {
data: () => ({
'slickComp': '',
}),
components: {
Slick: () => import('vue-slick')
},
mounted: function () {
this.$nextTick(function () {
this.slickComp = 'Slick'
})
},
}
</script>
Bascially this means the component isn't declared until the mounted function is called which is after all the server side rendering. And that should do it. Good luck.

I found another simple solution.
simply install "vue-slick" package to your nuxt project.
$ yarn add vue-slick
then component markup like below.
<template>
<component :is="slick" :options="slickOptions">
<div>Test1</div>
<div>Test2</div>
<div>Test3</div>
</component>
</template>
Finally set data and computed properties like this.
data() {
return {
slickOptions: {
slidesToShow: 1,
slidesToScroll: 1,
infinite: true,
centerMode: true,
},
};
},
computed: {
slick() {
return () => {
if (process.client) {
return import("vue-slick");
}
};
},
},
This solution prevents slick component importing globally as a plugin in nuxt config.

Related

Vue js always run a function to see if user is online or offline

Hi to all i want to find a way to see if user in my webapp is online or offline and run always! If user is offline wait 10 seconds to see if come back online and if not run a function!
Thanks all for the help!
Create a component OfflineComponent.vue like this:
<template>
<div>Offline component after 5 seconds!</div>
</template>
<script>
export default {
data() {
return {
showOnce: false,
}
},
mounted() {
this.startInterval()
},
methods: {
startInterval() {
window.setInterval(() => {
if (this.$nuxt.isOffline && !this.showOnce) {
this.runThisFunc()
this.showOnce = true
}
if (this.showOnce) {
clearInterval(window)
}
}, 5000)
},
runThisFunc() {
console.log('OFFLINE!')
},
},
}
</script>
Now import it inside the page you want. I use the main page:
<template>
<div v-if="$nuxt.isOffline">
<offline-component></offline-component>
</div>
<div v-else>You are Online!</div>
</template>
<script>
import OfflineComponent from '~/components/offlineComponent.vue'
export default {
name: 'IndexPage',
components: {
OfflineComponent,
},
}
</script>

vue can't querySelector for child component DOM element

I cannot search for child component DOM element, my settings are as follows:
pages/Login.vue
<template>
<section class="login">
<div v-show="step === 4" class="login__container">
<Test />
</div>
</section>
</template>
<script>
export default {
data () {
return {
step: 1
}
},
async mounted () {
this.step = 4
await this.$nextTick()
document.querySelector('.test') // NULL
},
}
</script>
components/Test.vue
<template>
<div class="test">
foo
</div>
</template>
setTimeout of course is not solution. I also try the same on other page, but without success. What am I doing wrong? I guess the problem must be somewhere in the template or project configuration
#edit
i tried to do the same effect on jsfiddle vue template and fresh nuxt project but no problem there
You could try to use ref instead of querySelector to manipulate the component DOM :
<template>
<section class="login">
<div v-show="step === 4" class="login__container">
<Test ref="test"/>
</div>
</section>
</template>
<script>
export default {
data () {
return {
step: 1
}
},
mounted () {
this.step = 4
let test=this.$refs.test
},
}
</script>
Another way to access child component is emitting event when its ready and created in DOM,
In the child element:
<template>
<div ref="test">foo</div>
</template>
<script>
export default {
mounted() {
this.$emit('childMounted', this.$refs.test)
}
}
...
In your parent:
<template>
<section class="login">
<div v-show="step === 4" class="login__container">
<Test #childMounted="childMounted"/>
</div>
</section>
</template>
<script>
export default {
data () {
return {
step: 1
}
},
methods: {
childMounted(childRef) {
// Try here
// childRef: your child component reference
}
}
}
</script>
This kind of code should work properly
parent.vue
<template>
<div>
<test ref="parentTest" #hook:mounted="selectChildElement"></test>
</div>
</template>
<script>
export default {
methods: {
selectChildElement() {
console.log(this.$refs.parentTest.$refs.test)
},
},
}
</script>
Test.vue component
<template>
<div ref="test">foo</div>
</template>
This is because of the way the parent and children components are mounted, as explained here: https://stackoverflow.com/a/44319825/8816585
As Brahim said, it is also better to use $refs in an SPA context, more info available here.
The #hook:mounted trick was taken from this answer and initially found in this dev.to post.
As I thought, the problem is with nuxt, namely auto-importing components.
I am using automatic component import in the nuxt configuration.
nuxt.config.js
components: [
{
path: '~/components',
pathPrefix: false,
},
],
This approach apparently breaks something, and only after manually importing the component did it work properly
import Test from '#/components/Test.vue'
export default {
name: 'LoginPage',
components: {
Test
},
So the nuxt configuration caused the problem. Thank you for all your help.

Async loading child component doesn't trigger v-if

Hi everyone and sorry for the title, I'm not really sure of how to describe my problem. If you have a better title feel free to edit !
A little bit of context
I'm working on a little personal project to help me learn headless & micro-services. So I have an API made with Node.js & Express that works pretty well. I then have my front project which is a simple one-page vue app that use vuex store.
On my single page I have several components and I want to add on each of them a possibility that when you're logged in as an Administrator you can click on every component to edit them.
I made it works well on static elements :
For example, here the plus button is shown as expected.
However, just bellow this one I have some components, that are loaded once the data are received. And in those components, I also have those buttons, but they're not shown. However, there's no data in this one except the title but that part is working very well, already tested and in production. It's just the "admin buttons" part that is not working as I expect it to be :
Sometimes when I edit some codes and the webpack watcher deal with my changes I have the result that appears :
And that's what I expect once the data are loaded.
There is something that I don't understand here and so I can't deal with the problem. Maybe a watch is missing or something ?
So and the code ?
First of all, we have a mixin for "Auth" that isn't implemented yet so for now it's just this :
Auth.js
export default {
computed: {
IsAdmin() {
return true;
}
},
}
Then we have a first component :
LCSkills.js
<template>
<div class="skills-container">
<h2 v-if="skills">{{ $t('skills') }}</h2>
<LCAdmin v-if="IsAdmin" :addModal="$refs.addModal" />
<LCModal ref="addModal"></LCModal>
<div class="skills" v-if="skills">
<LCSkillCategory
v-for="category in skills"
:key="category"
:category="category"
/>
</div>
</div>
</template>
<script>
import LCSkillCategory from './LCSkillCategory.vue';
import { mapState } from 'vuex';
import LCAdmin from '../LCAdmin.vue';
import LCModal from '../LCModal.vue';
import Auth from '../../mixins/Auth';
export default {
name: 'LCSkills',
components: {
LCSkillCategory,
LCAdmin,
LCModal,
},
computed: mapState({
skills: (state) => state.career.skills,
}),
mixins: [Auth],
};
</script>
<style scoped>
...
</style>
This component load each skills category with the LCSkillCategory component when the data is present in the store.
LCSkillCategory.js
<template>
<div class="skillsCategory">
<h2 v-if="category">{{ name }}</h2>
<LCAdmin
v-if="IsAdmin && category"
:editModal="$refs.editModal"
:deleteModal="$refs.deleteModal"
/>
<LCModal ref="editModal"></LCModal>
<LCModal ref="deleteModal"></LCModal>
<div v-if="category">
<LCSkill
v-for="skill in category.skills"
:key="skill"
:skill="skill"
/>
</div>
<LCAdmin v-if="IsAdmin" :addModal="$refs.addSkillModal" />
<LCModal ref="addSkillModal"></LCModal>
</div>
</template>
<script>
import LCSkill from './LCSkill.vue';
import { mapState } from 'vuex';
import LCAdmin from '../LCAdmin.vue';
import LCModal from '../LCModal.vue';
import Auth from '../../mixins/Auth';
export default {
name: 'LCSkillCategory',
components: { LCSkill, LCAdmin, LCModal },
props: ['category'],
mixins: [Auth],
computed: mapState({
name: function() {
return this.$store.getters['locale/getLocalizedValue']({
src: this.category,
attribute: 'name',
});
},
}),
};
</script>
<style scoped>
...
</style>
And so each category load a LCSkill component for each skill of this category.
<template>
<div class="skill-item">
<img :src="img(skill.icon.hash, 30, 30)" />
<p>{{ name }}</p>
<LCAdmin
v-if="IsAdmin"
:editModal="$refs.editModal"
:deleteModal="$refs.deleteModal"
/>
<LCModal ref="editModal"></LCModal>
<LCModal ref="deleteModal"></LCModal>
</div>
</template>
<script>
import LCImageRendering from '../../mixins/LCImageRendering';
import { mapState } from 'vuex';
import Auth from '../../mixins/Auth';
import LCAdmin from '../LCAdmin.vue';
import LCModal from '../LCModal.vue';
export default {
name: 'LCSkill',
mixins: [LCImageRendering, Auth],
props: ['skill'],
components: { LCAdmin, LCModal },
computed: mapState({
name: function() {
return this.$store.getters['locale/getLocalizedValue']({
src: this.skill,
attribute: 'name',
});
},
}),
};
</script>
<style scoped>
...
</style>
Then, the component with the button that is added everywhere :
LCAdmin.js
<template>
<div class="lc-admin">
<button v-if="addModal" #click="addModal.openModal()">
<i class="fas fa-plus"></i>
</button>
<button v-if="editModal" #click="editModal.openModal()">
<i class="fas fa-edit"></i>
</button>
<button v-if="deleteModal" #click="deleteModal.openModal()">
<i class="fas fa-trash"></i>
</button>
</div>
</template>
<script>
export default {
name: 'LCAdmin',
props: ['addModal', 'editModal', 'deleteModal'],
};
</script>
Again and I'm sorry it's not that I haven't look for a solution by myself, it's just that I don't know what to lookup for... And I'm also sorry for the very long post...
By the way, if you have some advice about how it is done and how I can improve it, feel free, Really. That how I can learn to do better !
EDIT :: ADDED The Store Code
Store Career Module
import { getCareer, getSkills } from '../../services/CareerService';
const state = () => {
// eslint-disable-next-line no-unused-labels
careerPath: [];
// eslint-disable-next-line no-unused-labels
skills: [];
};
const actions = {
async getCareerPath ({commit}) {
getCareer().then(response => {
commit('setCareerPath', response);
}).catch(err => console.log(err));
},
async getSkills ({commit}) {
getSkills().then(response => {
commit('setSkills', response);
}).catch(err => console.log(err));
}
};
const mutations = {
async setCareerPath(state, careerPath) {
state.careerPath = careerPath;
},
async setSkills(state, skills) {
state.skills = skills;
}
}
export default {
namespaced: true,
state,
actions,
mutations
}
Career Service
export async function getCareer() {
const response = await fetch('/api/career');
return await response.json();
}
export async function getSkills() {
const response = await fetch('/api/career/skill');
return await response.json();
}
Then App.vue, created() :
created() {
this.$store.dispatch('config/getConfigurations');
this.$store.dispatch('certs/getCerts');
this.$store.dispatch('career/getSkills');
this.$store.dispatch('projects/getProjects');
},
Clues
It seems that if I remove the v-if on the buttons of the LCAdmin, the button are shown as expected except that they all show even when I don't want them to. (If no modal are associated)
Which give me this result :
Problem is that refs are not reactive
$refs are only populated after the component has been rendered, and they are not reactive. It is only meant as an escape hatch for direct child manipulation - you should avoid accessing $refs from within templates or computed properties.
See simple demo below...
const vm = new Vue({
el: "#app",
components: {
MyComponent: {
props: ['modalRef'],
template: `
<div>
Hi!
<button v-if="modalRef">Click!</button>
</div>`
}
},
data() {
return {
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<my-component :modal-ref="$refs.modal"></my-component>
<div ref="modal">I'm modal placeholder</div>
</div>
The solution is to not pass $ref as prop at all. Pass simple true/false (which button to display). And on click event, $emit the event to the parent and pass the name of the ref as string...

Ckeditor4-vue with Nuxt.js how to access CKEDITOR

I have started using ckeditor4-vue
https://ckeditor.com/docs/ckeditor4/latest/guide/dev_vue.html#using-the-component-locally
<template>
<div>
<ckeditor
v-model="formData"
:config="editorConfig"
#input="$emit('update:editorData', formData)"
></ckeditor>
</div>
</template>
<script>
import CKEditor from 'ckeditor4-vue';
export default {
components: {
ckeditor: CKEditor.component
},
props: ['editorData'],
data() {
return {
formData: this.editorData,
editorConfig: {}
};
},
mounted() {
CKEDITOR.disableAutoInline = true;
}
};
</script>
However I can't find how I can use CKEDITOR, in this example, I have CKEDITOR is not defined.
Thank you
make sure you're calling it the right way, CKEDITOR <> CKEditor.
try removing your mounted and this should works

relative module was not found: vue-lottie

After a fresh build with vue-cli (3.0.0-rc.5) the path to the lottie module can't be reached. Should I play with the configs?
./lottie.vue in ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/HelloWorld.vue?vue&type=script&lang=js&
<template>
<div id="app">
<lottie :options="defaultOptions" :height="400" :width="400" v-on:animCreated="handleAnimation"/>
<div>
<p>Speed: x{{animationSpeed}}</p>
<input type="range" value="1" min="0" max="3" step="0.5"
v-on:change="onSpeedChange" v-model="animationSpeed">
</div>
<button v-on:click="stop">stop</button>
<button v-on:click="pause">pause</button>
<button v-on:click="play">play</button>
</div>
<script>
import Lottie from './lottie.vue';
import * as animationData from './assets/data.json';
export default {
name: 'app',
components: {
'lottie': Lottie
},
data() {
return {
defaultOptions: {animationData: animationData},
animationSpeed: 1
}
},
methods: {
handleAnimation: function (anim) {
this.anim = anim;
},
stop: function () {
this.anim.stop();
},
play: function () {
this.anim.play();
},
pause: function () {
this.anim.pause();
},
onSpeedChange: function () {
this.anim.setSpeed(this.animationSpeed);
}
}
}
</script>
If it still doesn't work change animationData to animationData.default in defaultOptions
defaultOptions: { animationData: animationData.default }
If you are using vue-lottie package then the import should be
import Lottie from 'vue-lottie';
This is because lottie package is located in the node_modules folder and you have to provide the right path or use direct package name import.
On a side note, I believe the current version of Vue cli is v3.1.1 so you should definitely upgrade.