Nuxt 3 - how to access plugin injections from components? - vue.js

Using Nuxt 3 and vue-gtag, what is the right way to access $gtag from components?
plugins/gtag.client.js:
import VueGtag from 'vue-gtag';
export default defineNuxtPlugin(nuxtApp => {
const router = useRouter();
nuxtApp.vueApp.use(
VueGtag,
{
config: {
id: '...'
}
},
router
);
});
In Nuxt 2, this.$gtag was accessible from component file.
In Nuxt 3, I can't seem to find it:
const nuxtApp = useNuxtApp();
nuxtApp.$gtag //undefined
Looking at the source code, it seems to be defined correctly, so I don't think it's a problem with the plugin itself.
app.config.globalProperties.$gtag = api;

I have same issue when define the domToImage plugin in nuxt 3. I found a solution as follow. Hope to help you.
Return provide in nuxt plugin:
import domtoimage from "dom-to-image-more";
export default defineNuxtPlugin((nuxtApp) => {
// nuxtApp.vueApp.use(domtoimage)
return {
provide: {
domtoimage
}
}
})
Use in component:
const print = () => {
console.log("Print ...")
const { $domtoimage } = useNuxtApp()
$domtoimage.toPng(printMeDiv)
.then((dataUrl) => {
console.log(dataUrl)
})
}
}

Related

Nuxt Bridge : alternative to `useFetch()` in #nuxtjs/composition-api

I'm migrating from #nuxtjs/composition-api package to Nuxt Bridge and I see that useFetch is available only with Nuxt 3.
Before, I was using the pattern below:
const { state: userState, getUserList } = useUserList()
const { state: groupState, getGroupList } = useGroupList()
// ...
const { fetchState } = useFetch(async () => {
await Promise.all([
getUserList(),
getGroupList(),
// ...
])
})
And I could use fetchState.pending to display a loader until everything was loaded.
How to have the behavior with Nuxt Bridge knowing that only useLazyAsyncData and useLazyFetch are compatible?

Upgraded to Vue 2.7 and now getting a bunch of warnings: [Vue warn]: Vue 2 does not support readonly arrays

Background
I recently upgraded from Vue v2.6.14 to Vue 2.7 by following this guide: https://blog.vuejs.org/posts/vue-2-7-naruto.html.
I made some changes (e.g., removing #vue/composition-api and vue-template-compiler, upgrading to vuex-composition-helpers#next, etc.).
Problem
The application loads for the most part, but now I get a ton of console errors:
[Vue warn]: Vue 2 does not support readonly arrays.
It looks like even just console.log(workspaces.value); (see code below) raises the warning.
Question
How do I resolve this issue?
Thank you!
Code
<script lang="ts">
import {
defineComponent,
onMounted,
computed,
} from 'vue';
import { createNamespacedHelpers } from 'vuex-composition-helpers';
import {
modules,
actionTypes,
getterTypes,
} from '#/store/types';
import _ from 'lodash';
const workspaceModule = createNamespacedHelpers(modules.WORKSPACE_MODULE);
export default defineComponent({
setup() {
const { newWorkspace, listWorkspaces } = workspaceModule.useActions([
actionTypes.WorkspaceModule.NEW_WORKSPACE,
actionTypes.WorkspaceModule.LIST_WORKSPACES,
]);
const { workspaces } = workspaceModule.useGetters([
getterTypes.WorkspaceModule.GET_WORKSPACES,
]);
onMounted(async () => {
await listWorkspaces({
Archived: false,
Removed: false,
});
console.log(workspaces.value);
});
return {
/*
workspacesSorted: computed(() => {
return _.orderBy(workspaces.value, ['LastUpdated'], ['desc']);
}),
*/
}
}
});
</script>
src/store/modules/workspace/getters.ts
import { GetterTree } from 'vuex';
import { WorkspaceState } from './types';
import { RootState } from '../../types';
import { getterTypes } from '../../types';
export const getters: GetterTree<WorkspaceState, RootState> = {
[getterTypes.WorkspaceModule.GET_WORKSPACES](context: WorkspaceState) {
return context.Workspaces;
},
[getterTypes.WorkspaceModule.GET_ALL_WORKSPACES](context: WorkspaceState) {
return context.AllWorkspaces;
}
}
src/store/modules/workspace/actions.ts
export const actions: ActionTree<WorkspaceState, RootState> = {
async [actionTypes.WorkspaceModule.LIST_WORKSPACES]({ commit }, payload: ListWorkspace) {
const wss = await list(payload.Archived, payload.Removed);
wss.forEach((ws) => {
ws.Archived = payload.Archived;
ws.Removed = payload.Removed;
});
commit(mutationTypes.WorkspaceModule.SET_WORKSPACES, wss);
},
};
src/store/modules/workspace/actions.ts
export const mutations: MutationTree<WorkspaceState> = {
[mutationTypes.WorkspaceModule.SET_WORKSPACES](ctx: WorkspaceState, wss: Workspace[]) {
ctx.Workspaces = wss;
},
};
src/service/useWorkspace.ts
const list = async(archived: boolean, removed: boolean) => {
const res = await get<Workspace[], AxiosResponse<Workspace[]>>('/workspace/list', {
params: {
archived,
removed,
}
});
return success(res);
};
When I call store.state.WorkspaceModule.Workspaces directly (either in the console or in computed), I get no errors:
import { useStore } from '#/store';
export default defineComponent({
setup() {
const store = useStore();
onMounted(async () => {
await listWorkspaces({
Archived: false,
Removed: false,
});
console.log(store.state.WorkspaceModule.Workspaces);
});
return {
workspacesSorted: computed(() =>
store.state.WorkspaceModule.Workspaces
),
}
}
});
This might be because workspaces is based on a getter, which are read-only. As mentioned in the blog you were referring to, readonly is not supported for arrays in Vue 2.7:
readonly() does create a separate object, but it won't track newly added properties and does not work on arrays.
It was (partially) supported for arrays in the Vue 2.6 Composition Api Plugin though:
readonly() provides only type-level readonly check.
So that might be causing the error. If it is mandatory for you, you might need to upgrade to vue3, or stick with 2.6 for a while. The composition Api plugin is maintained until the end of this year...
A workaround may be to skip the getter and access the state directly, since it is a quite simple getter which only returns the current state of Workspaces.
Hope this helps.

How to Implement nuxtServerInit Action to load data from server-side on the initial load in Pinia (Nuxt3)

My Code:
export const useMenuStore = defineStore("menuStore", {
state: () => ({
menus: [],
}),
actions: {
async nuxtServerInit() {
const { body } = await fetch("https://jsonplaceholder.typicode.com/posts/1").then((response) => response.json());
console.log(body);
this.menus = body;
resolve();
},
},
});
NuxtServerInit is not working on initial page render on nuxt js vuex module mode.Anyone know this error please help me.
NuxtServerInit is not implemented in Pinia, but exists a workaround.
Using Pinia alongside Vuex
// nuxt.config.js
export default {
buildModules: [
'#nuxtjs/composition-api/module',
['#pinia/nuxt', { disableVuex: false }],
],
// ... other options
}
then Include an index.js file inside /stores with a nuxtServerInit action which will be called from the server-side on the initial load.
// store/index.js
import { useSessionStore } from '~/stores/session'
export const actions = {
async nuxtServerInit ({ dispatch }, { req, redirect, $pinia }) {
if (!req.url.includes('/auth/')) {
const store = useSessionStore($pinia)
try {
await store.me() // load user information from the server-side before rendering on client-side
} catch (e) {
redirect('/auth/login') // redirects to login if user is not logged in
}
}
}
}
In Nuxt2, the Nuxt will run the code in nuxtServerInit() of store/index.js on the server-side to boot the app.
However, in Nuxt3, there is no specific place to write the boot code, you can write the boot code anywhere instead of in nuxtServerInit() of store/index.js.
It might be helpful, especially when you need to send a request before boosting the app.
your pinia file may define like following:
store/menu.js
import { defineStore } from 'pinia';
export const useMenuStore = defineStore('menuStore', {
state: () => ({
_menus: [],
}),
getters: {
menus() {
return this._menus;
}
},
actions: {
async boot() {
const { data } = await useFetch('https://jsonplaceholder.typicode.com/posts/1');
this._menus = data;
}
}
});
Then, create a plugin which named as *.server.[ts|js], for example init.server.js
(.sever.js tail will let the file only run in server side)
plugins/init.server.js
import { defineNuxtPlugin } from '#app';
import { useMenuStore } from '~/store/menu.js';
export default defineNuxtPlugin(async (nuxtApp) => {
const menu = useMenuStore(nuxtApp.$pinia);
await menu.boot();
});
nuxt.config.js
modules: [
'#pinia/nuxt',
],
There is an entire example of SSR Nuxt3 with authorization that may help

Check if vuex-persist has restored data in Nuxt project

I have added Vuex-Persist and Vuex-ORM to my Nuxt project. When the application starts for the first time I want to add some boilerplate data.
In my default.vue layout I have added a created function to add this dummy data.
<script>
import Project from '../models/Project';
export default {
created () {
// I'm Using Vuex-Orm to check if there are any projects stored
if (Project.query().count() === 0) {
Project.insert({ data: [{ title: 'My first project' }] })
}
}
}
</script>
When the application is reloaded and opens for the second time, I would expect that Project.query().count()
returns 1. But it will always return 0 because vuex-persist isn't done restoring the local data yet.
According to the docs this would be the solution
import { store } from '#/store' // ...or wherever your `vuex` store is defined
const waitForStorageToBeReady = async (to, from, next) => {
await store.restored
next()
}
store.defined is undefined and same goes for this.$store.
That comment highlights my exact question "Where is my vuex store defined?"
i think you have to put the whole thing in a route guard.
create a route-guard.js plugin like this. but I haven't tested the whole thing, hope it helps you further.
export default function ({app}) {
const waitForStorageToBeReady = async (to, from, next) => {
await store.restored
next()
}
app.router.beforeEach(waitForStorageToBeReady);
}
Another option is to put a getter in computed and watch it:
export default {
computed: {
persistState() {
return this.store.getter['get_persis_state'];
}
},
watch: {
persistState(newVal) {
// check new val
}
}
}
I followed the instructions from vuex-persist for Nuxt and made a plugin file, like this:
// ~/plugins/vuex-persist.js
import VuexPersistence from 'vuex-persist'
export default ({ store }) => {
window.onNuxtReady(() => {
new VuexPersistence({
/* your options */
}).plugin(store);
});
}
window.onNuxtReady caused the plugin to be loaded after all other code had run. So I didn't matter if I made a router-guard.js plugin or tried it in the layout/default.vue file.
I ended up with the quick fix:
// ~/plugins/vuex-persist.js
import VuexPersistence from 'vuex-persist'
export default ({ store }) => {
window.onNuxtReady(() => {
new VuexPersistence().plugin(store);
if (Project.query().count() === 0) {
Project.insert({ data: [{ title: 'My first project' }] })
}
});
}

How to attach axios / axios interceptor to Nuxt globally ?

how would i go about attaching axios / axios interceptor globally to nuxt (so its available everywhere), same how i18n is attached ?
The idea is that i would like to have a global axios interceptor that every single request goes through that interceptor.
Thanks
you can create a plugin called axios (/plugins/axios.js)
import Vue from 'vue';
import axios from 'axios';
axios.interceptors.request.use((config) => {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
Vue.use(axios);
then define this in nuxt.config.js
module.exports = {
//....
plugins: [
'~/plugins/axios',
],
//....
};
thats all, your interceptor is now working globally
It's hidden in the documentation - https://nuxtjs.org/docs/2.x/directory-structure/plugins
See number 3 of the first photo:
// plugins/axios.js
export default function ({ $axios, redirect }) {
$axios.onError(error => {
if (error.response.status == 404) {
redirect('/sorry')
}
})
}
then define this in nuxt.config.js
module.exports = {
//....
plugins: [
'~/plugins/axios',
],
//....
};
Maybe will be helpful for someone.
It just sets the lang parameter for every request.
Сreate a plugin called axios (/plugins/axios.js). Put it there:
export default function ({ $axios, app, redirect }) {
$axios.onRequest(config => {
config.params = config.params || {}; // get existing parameters
config.params['lang'] = app.i18n.locale;
})
$axios.onError(error => {
const code = parseInt(error.response && error.response.status)
if (code === 400) {
redirect('/400')
}
})
}
Add in nuxt.config.js:
module.exports = {
plugins: [
'~/plugins/axios'
]
};
Create a new module, call it request.js for example.
import axios from 'axios'
const instance = axios.create({
baseURL: 'http://example.org' // if you have one
})
// Put all interceptors on this instance
instance.interceptors.response.use(r => r)
export default instance
Then simply import that instance whenever you need it and use it like it was a normal axios instance:
import request from './request'
await request.get('/endpoint')
// or use promises
request.get('/endpoint').then(data => data)
If you really need it globally you can use the following code in your entry point of the application:
import request from './request'
global.request = request
// use it:
await request.get('example.org')
Or you can add it to the vue protype
Vue.prototype.$request = request
// in your component:
this.$request.get()
I'd advice against it though.