Critical dependency: require function in nuxt project - vue.js

I am recieving "Critical dependency: require function is used in a way in which dependencies cannot be statically extracted friendly-errors 16:21:14" error when using the package scrollMonitor in my nuxt project
plugins/scroll-monitor.js
import Vue from 'vue';
// your imported custom plugin or in this scenario the 'vue-session' plugin
import ScrollMonitor from 'scrollmonitor';
Vue.use(ScrollMonitor);
nuxt.config.js
plugins: [
'~/plugins/wordpress-api',
{ src: '~/plugins/scroll-monitor.js', ssr: false }
],
build: {
/*
** You can extend webpack config here
*/
vendor: ['scrollmonitor'],
extend(config, ctx) {
}
}
At my index.vue file
let scrollmonitor
if (process.client) {
scrollmonitor = require('scrollmonitor')
}
More context
Still not working.
I am using new computer, at my old one everything is working fine.
index.vue
<template>
<div class="index page-padding-top">
<TheHero
:scaledUpDot="scaledUpDot"
:isFirstImageVisible="isFirstImageVisible"
/>
<ProjectsList :projects="projects" />
</div>
</template>
<script>
import { mapGetters } from "vuex";
import TheHero from "~/components/TheHero";
import ProjectsList from "~/components/ProjectsList";
export default {
async mounted () {
if (process.browser) {
const scrollMonitor = await import('scrollmonitor')
Vue.use(scrollMonitor)
console.log('HELLO FROM MOUNTED')
}
},
name: "Index",
components: { TheHero, ProjectsList},
data() {
return {
scaledUpDot: false,
isFirstImageVisible: false,
};
},
computed: {
...mapGetters({
projects: "getProjects",
}),
},
mounted() {
this.handleScaling();
this.hideScrollSpan();
},
destroyed() {
this.handleScaling();
this.hideScrollSpan();
},
methods: {
handleScaling() {
if (process.client) {
const heroSection = document.querySelectorAll(".hero");
const heroSectionWtcher = scrollMonitor.create(heroSection, 0);
heroSectionWtcher.enterViewport(() => {
this.scaledUpDot = true;
});
}
},
hideScrollSpan() {
if (process.client) {
const images = document.querySelectorAll(".projects-home img");
const firstImage = images[0];
const imageWatcher = scrollMonitor.create(firstImage, -30);
imageWatcher.enterViewport(() => {
this.isFirstImageVisible = true;
});
}
},
},
};
</script>
In my old computer I have it imported like this :
import { mapGetters } from 'vuex'
import scrollMonitor from 'scrollmonitor'
But when I want to run this in a new one I get an error that window is not defined
So I have started to add this plugin in other way and still not working

Still not working.
I am using new computer, at my old one everything is working fine.
index.vue
<template>
<div class="index page-padding-top">
<TheHero
:scaledUpDot="scaledUpDot"
:isFirstImageVisible="isFirstImageVisible"
/>
<ProjectsList :projects="projects" />
</div>
</template>
<script>
import { mapGetters } from "vuex";
import TheHero from "~/components/TheHero";
import ProjectsList from "~/components/ProjectsList";
export default {
async mounted () {
if (process.browser) {
const scrollMonitor = await import('scrollmonitor')
Vue.use(scrollMonitor)
console.log('HELLO FROM MOUNTED')
}
},
name: "Index",
components: { TheHero, ProjectsList},
data() {
return {
scaledUpDot: false,
isFirstImageVisible: false,
};
},
computed: {
...mapGetters({
projects: "getProjects",
}),
},
mounted() {
this.handleScaling();
this.hideScrollSpan();
},
destroyed() {
this.handleScaling();
this.hideScrollSpan();
},
methods: {
handleScaling() {
if (process.client) {
const heroSection = document.querySelectorAll(".hero");
const heroSectionWtcher = scrollMonitor.create(heroSection, 0);
heroSectionWtcher.enterViewport(() => {
this.scaledUpDot = true;
});
}
},
hideScrollSpan() {
if (process.client) {
const images = document.querySelectorAll(".projects-home img");
const firstImage = images[0];
const imageWatcher = scrollMonitor.create(firstImage, -30);
imageWatcher.enterViewport(() => {
this.isFirstImageVisible = true;
});
}
},
},
};
</script>
In my old computer I have it imported like this :
import { mapGetters } from 'vuex'
import scrollMonitor from 'scrollmonitor'
But when I want to run this in a new one I get an error that window is not defined
So I have started to add this plugin in other way and still not working

Related

vuex unknown mutation type: setPatient

I'm using vue 3 with composition api and vuex 4, I've done it this way before but now its throwing that error.
Here's my store/index.js
import { createStore } from "vuex";
export const store = new createStore({
state: {
patient: [],
},
mutations: {
setPatient(state, payload) {
state.patient = payload;
},
},
getters: {
getPatient(state) {
return state.patient;
},
getAppointment(state) {
return state.patient.appointments;
},
},
})
app.js
require('./bootstrap');
import { createApp, h } from 'vue';
import { createInertiaApp } from '#inertiajs/inertia-vue3';
import { InertiaProgress } from '#inertiajs/progress';
import {store} from './Store'
const { RayPlugin } = require('vue-ray');
window.$ = window.jQuery = require("jquery");
const appName = window.document.getElementsByTagName('title')[0]?.innerText || 'Laravel';
createInertiaApp({
title: (title) => `${title} - ${appName}`,
resolve: (name) => require(`./Pages/${name}.vue`),
setup({ el, app, props, plugin }) {
return createApp({ render: () => h(app, props) })
.use(plugin)
.use(store)
.use(RayPlugin, { interceptErrors: true, host: '127.0.0.1', port: 23517 })
.mixin({ methods: { route } })
.mount(el);
},
});
InertiaProgress.init({ color: '#4B5563' });
And following the documentation, on my component I did the following:
import { useStore } from 'vuex'
import {onMounted, reactive, ref} from "vue";
export default {
props: {
patient: {
type: Object,
required: true
}
},
setup(props) {
const store = useStore();
onMounted(() => {
store.commit('setPatient', props.patient);
})
}
}
So far I've done this before, but using the composition api is new for me, so I couldn't find where the error is

How to use Pinia with Nuxt, composition-api (vue2) and SSR?

I'm trying to get Pinia to work in Nuxt with SSR (server-side rendering).
When creating a page without Pinia, it works:
<script>
import { reactive, useFetch, useContext } from '#nuxtjs/composition-api'
export default {
setup() {
const { $axios } = useContext()
const invitesStore = reactive({
invites: [],
loading: true,
})
useFetch(async () => {
invitesStore.loading = true
await $axios.$get('invite/registermember').then((result) => {
invitesStore.loading = false
invitesStore.invites = result.invites
})
})
return {
invitesStore,
}
},
}
</script>
But when introducing Pinia, I get the error "Converting circular structure to JSON --> starting at object with constructor 'VueRouter'"
I'm using Pinia this way:
// /store/invitesStore.js
import { defineStore } from 'pinia'
// useStore could be anything like useUser, useCart
export const useInvitesStore = defineStore({
// unique id of the store across your application
id: 'storeId',
state() {
return {
invites: [],
loading: true,
}
},
})
<script>
import { useInvitesStore } from '#/store/invitesStore'
import { reactive, onMounted, useFetch, useContext } from '#nuxtjs/composition-api'
export default {
setup() {
const { $axios } = useContext()
const invitesStore = useInvitesStore()
useFetch(async () => {
invitesStore.loading = true
await $axios.$get('invite/registermember').then((result) => {
invitesStore.loading = false
invitesStore.invites = result.invites
})
})
return {
invitesStore,
}
},
}
</script>
Is it possible to get this to work? How?

IONIC + Vue.js not working getters in VUEX

Hello developers I'm working with Ionic and Vue+Vuex in this app, but eventually, I can't access my state from my getters for some reason.
As usually the management state is settled for that purpose with actions getters, mutations, and state.
import { createStore } from "vuex";
const urlLogin = "http://localhost:3006/auth";
const urlUser = "http://localhost:3006/user";
const store = createStore({
state() {
return {
userRegisteredState: false,
allUsersState: [],
};
},
mutations: {
commit_get_all_users(state, payload) {
console.log(payload);
return (state.allUsersState = payload);
},
},
getters: {
getterGetAllUsers(state) {
console.log(state);//checking all state (See image )
console.log(state.allUsersState)//checking only the item I want to consume from state (See image )
return state.allUsersState;
},
},
actions: {
//=================================================================
//============================================================
async getAllUsers({ commit }) {
fetch(`${urlUser}/get/all/users`, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8100",
},
})
.then((result) => {
return result.json();
})
.then((result) => {
console.log(result);
commit("commit_get_all_users", result);
})
.catch((error) => {
console.log(error);
error;
});
},
},
});
export default store;
then on my component , in this case that one referring to get all users I set this logic:
<template>
...some tags...
</template>
<script>
import { mapActions, mapGetters } from "vuex";
export default {
name: "AllUsersComponent",
data() {
return {
allUsers: [],
};
},
methods: {
...mapActions(["getAllUsers"]),
getAllUsersFront() {
this.$store.dispatch("getAllUsers");
},
...some methods....
},
computed: {
...mapGetters(["getterGetAllUsers"]),
getterGetAllUsersFunction() {
console.log(this.$store.getters.getterGetAllUsers);
return this.$store.getters.getterGetAllUsers;
},
},
async mounted() {
this.getAllUsersFront();
},
created() {
this.getAllUsersFront();
this.getterGetAllUsersFunction;
console.log(this.getterGetAllUsersFunction);
},
watch: {},
};
</script>
<style>
</style>
On my main.js file store is imported according to IONC in this way
import { createApp } from "vue";
import './gapi.js'
import App from "./App.vue";
import router from "./router";
import store from "./store/index"; //importando vuex
import loginComponentTag from "./components/Login";
import allUsersComponentTag from "./components/all-users-component"
// import GoogleSignInButton from 'vue-google-signin-button-directive'
import { IonicVue } from "#ionic/vue";
/* Core CSS required for Ionic components to work properly */
import "#ionic/vue/css/core.css";
/* Basic CSS for apps built with Ionic */
import "#ionic/vue/css/normalize.css";
import "#ionic/vue/css/structure.css";
import "#ionic/vue/css/typography.css";
/* Optional CSS utils that can be commented out */
import "#ionic/vue/css/padding.css";
import "#ionic/vue/css/float-elements.css";
import "#ionic/vue/css/text-alignment.css";
import "#ionic/vue/css/text-transformation.css";
import "#ionic/vue/css/flex-utils.css";
import "#ionic/vue/css/display.css";
/* Theme variables */
import "./theme/variables.css";
const app = createApp(App)
.use(IonicVue)
.use(store)
.use(router)
app.component("LoginComponent", loginComponentTag);
app.component("AllUsersComponent",allUsersComponentTag)
router.isReady().then(() => {
app.mount("#app");
});
And my vue.config.js is settled in this way:
module.exports = {
devServer: {
proxy: "http://localhost:8100",
},
};
I checked my logs and eventually.
Literally, the situation is that despite having my state populated with data, unless I retrieve the whole state, I can't retrieve a particular item from it, cause the response is nothing.
Is there any configuration I'm omitting in this process I need to have in mind?

Rollup Vue 3 Dynamic img src

Dynamic img src were handled by Webpack's require:
<img :src="require(`#/assets/${posts.img}`)" alt="">
How to do this on a vite-app that uses Rollup?
you can refer to docs of webpack-to-viteļ¼š
use Vite's API import.meta.glob to convert dynamic require(e.g. require('#assets/images/' + options.src)), you can refer to the following steps
create a Model to save the imported modules, use async methods to dynamically import the modules and update them to the Model
// src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
const assets = import.meta.glob('../assets/**')
Vue.use(Vuex)
export default new Vuex.Store({
state: {
assets: {}
},
mutations: {
setAssets(state, data) {
state.assets = Object.assign({}, state.assets, data)
}
},
actions: {
async getAssets({ commit }, url) {
const getAsset = assets[url]
if (!getAsset) {
commit('setAssets', { [url]: ''})
} else {
const asset = await getAsset()
commit('setAssets', { [url]: asset.default })
}
}
}
})
use in .vue SFC
// img1.vue
<template>
<img :src="$store.state.assets['../assets/images/' + options.src]" />
</template>
<script>
export default {
name: "img1",
props: {
options: Object
},
watch: {
'options.src': {
handler (val) {
this.$store.dispatch('getAssets', `../assets/images/${val}`)
},
immediate: true,
deep: true
}
}
}
</script>

have to add 3 components to one page

In my project, I have 3 components. one component is already showing on the page and now I want to add those 2 components with that component. The code is in below,
<template>
<component v-bind:is="currentComponent" ></component>
</template>
<script>
import { ROAST_CONFIG } from '../../../config/config.js';
import ZoneIndex from './components/zone/Index';
import { listen } from '../../../util/history.js';;
import axios from 'axios'
let baseUrl = ROAST_CONFIG.API_URL;
export default {
name: 'LocationsView',
layout: 'admin/layouts/default/defaultLayout',
middleware: 'auth',
components: {
'zone-index' : ZoneIndex,
},
data() {
return { currentComponent:'','stateId':''}
},
methods: {
updateCurrentComponent(){
console.log(this.$route.name);
let vm = this;
let route = vm.$route;
if(this.$route.name == "Locations"){
this.currentComponent = "zone-index";
}
}
},
mounted() {
let vm = this;
let route = this.$route;
window.addEventListener('popstate',this.updateCurrentComponent);
},
created() {
this.updateCurrentComponent();
}
}
The ZoneIndex component is showing in the code. The other 2 components are CountryIndex and StateIndex.
The correct way to carry out your procedure would be.
<template>
<div>
<zone-index></zone-index>
<state-index></state-index>
<country-index></country-index>
</div>
</template>
<script>
import ZoneIndex from './components/zone/Index';
import CountryIndex from '...way';
import StateIndex ryIndex from '...way';
import { ROAST_CONFIG } from '../../../config/config.js';
import { listen } from '../../../util/history.js';;
import axios from 'axios'
let baseUrl = ROAST_CONFIG.API_URL;
export default {
name: 'LocationsView',
layout: 'admin/layouts/default/defaultLayout',
middleware: 'auth',
components: { ZoneIndex, CountryIndex, StateIndex },
data() {
return { currentComponent:'','stateId':''}
},
methods: {
updateCurrentComponent(){
console.log(this.$route.name);
let vm = this;
let route = vm.$route;
if(this.$route.name == "Locations"){
this.currentComponent = "zone-index";
}
}
},
mounted() {
let vm = this;
let route = this.$route;
window.addEventListener('popstate',this.updateCurrentComponent);
},
created() {
this.updateCurrentComponent();
}
}