How to create a helper function in NuxtJs to use inside vuex and components? - vue.js

I want to create a plugin for Nuxtjs to log everything I want only in client mode, something like this :
// ~/plugins/client-log.js
export default ({ app }, inject) => {
app.clog = string => console.log(string)
}
This plugin is working in components where I have access to context for example:
export default {
fetch({app}){
app.clog("some string")
}
};
But I want to be able to use it inside vuex (actions, mutations...). How can I do that?
Thanks in advance.

You're so close, you just need to change one thing:
// ~/plugins/client-log.js
export default ({ app }, inject) => {
inject('clog', string => console.log(string))
}
Then you're able to call it like:
export default {
fetch({app}){
// Note: inject will automatically prefix with a "$"
app.$clog("some string")
},
mounted() {
// this.$clog can also be accessed within vuex
this.$clog("I'm in a component")
}
};

Related

Access Nuxt Router in plugin

I've created a Nuxt plugin that is loaded in the config file with some global functions. In one function, I'd like to access the router, and push to a new route. I am getting an error that router is undefined. Can someone help me understand how I access the router here, if its not attached to the context.
export default (context, inject) => {
const someFunction = () => {
context.router.push({ name: 'route-name' } })
}
}
Try to destruct the context then use app to access the router :
export default ({app}, inject) => {
const someFunction = () => {
app.router.push({ name: 'route-name' } })
}
}
I figured this out. When using context, you can access the router, like this:
context.app.router

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' }] })
}
});
}

Understanding context and app methods in NUXT

I am trying to use bugsnagClient and its notify method in plugins/axios.js I have this code in plugins/bugsnag.js
import Vue from "vue"
import bugsnag from "#bugsnag/js"
import bugsnagVue from "#bugsnag/plugin-vue"
// const bugsnagClient = bugsnag(`${process.env.BUGSNAG_API_KEY}`)
var bugsnagClient = bugsnag({
apiKey: "",
notifyReleaseStages: ["production"]
})
bugsnagClient.use(bugsnagVue, Vue)
I want to attach a method to app or context as
export default ({ app }, inject) => {
function bugsnagNotify(error) {
return bugsnagClient.notify(new Error(error))
}
// Set the function directly on the context.app object
app.bugsnagNotify = bugsnagNotify
}
And I want to use it in plugins/axios.js
export default function({ store, app }) {
if (store.getters.token) {
console.log(app.bugsnagNotify("ss"))
app.$axios.setToken(store.getters.token, "Bearer")
} else {
//app.$bugsnag.notify(new Error("Bearer tooken is missing in Axios request."))
}
}
In this file, when I do console.log for just app
I can see bugsnagNotify: ƒ bugsnagNotify(error)
but when I call app.bugsnagNotify("error") I only get error such as VM73165:37 TypeError: app.bugsnagNotify is not a function
I have also tried this in plugins/bugsnag.js
export default (ctx, inject) => {
inject('bugsnag', bugsnagClient)
}
I only get an error as
app.$bugsnag.notify(new Error("Bearer tooken is missing in Axios request."))
If you are injecting into context inside one plugin and want to use that function inside another, you need to make sure that the plugin in which you are injecting comes first inside nuxt.config.js
...
plugins: [
'~/plugins/bugsnag.js',
'~/plugins/axios.js'
],
...

Nuxt: Vuex commit or dispatch message outside vuejs component

I have an application in nuxt that I want to connect to a websocket, I have seen examples where the callback to receive messages is placed inside a component, but I do not think ideal, I would like to place the callback inside my store, currently my code is something like this
//I'm using phoenix websocket
var ROOT_SOCKET = `wss://${URL}/socket`;
var socket = new Socket(ROOT_SOCKET);
socket.connect()
var chan = socket.channel(`connect:${guid}`);
chan.join();
console.log("esperando mensj");
chan.on("translate", payload => {
console.log(JSON.stringify(payload));
<store>.commit("loadTranslation",payload) //<- how can I access to my store?
})
chan.onError(err => console.log(`ERROR connecting!!! ${err}`));
const createStore = () => {
return new Vuex.Store({
state: {},
mutations:{
loadTranslation(state,payload){...}
},
....
})}
how can I access to my store inside my own store file and make a commit??? is it possible?...
I know there is a vuex plugin but I can't really understand well the documentation and I'll prefer build this without that plugin
https://vuex.vuejs.org/guide/plugins.html
thank you guys...hope you can help me...
You can do it in nuxt plugin https://nuxtjs.org/guide/plugins/
export default {
plugins: ['~/plugins/chat.js']
}
// chat.js
export default ({ store }) => {
your code that use store here
}

How to use own JS as a plugin using Nuxt.js

I am using nuxt.js. I have a helper.js script inside plugins folder which has a simple Test() function. Now how can I can call the Test() method inside pages which is in helper.js file.
helper.js file:
export default function Test() {
return 'This is test'
}
to access your global methods entire application:
1-create ./plugins/helpers.js .
2-edit ./plugins/helpers.js :
import Vue from 'vue'
Vue.mixin({
methods:{
mySpecialMethod(value){
console.log(value)
},
}
})
3-edit ./nuxt.config.js :
plugins: [
...
{ src: '~/plugins/helpers' },
...
],
now you can access your global method by:
this.mySpecialMethod()
Using the inject method
There is actually an easy way to do this by using the 'inject' method.
As described in the docs...
The plugins directory contains JavaScript plugins that you want to run before instantiating the root Vue.js Application. This is the place to add Vue plugins and to inject functions or constants. Every time you need to use Vue.use(), you should create a file in plugins/ and add its path to plugins in nuxt.config.js.
in your plugin simply use inject like this:
export default ({ app }, inject) => {
inject('myInjectedFunction', (string) => console.log('That was easy!', string))
}
and in your components you can use it as follows:
export default {
mounted(){
this.$myInjectedFunction('works in mounted')
},
asyncData(context){
context.app.$myInjectedFunction('works with context')
}
}
"Manual" injection
If you plan on injecting something yourself check out the Vue Docs on Adding Instance properties
There may be data/utilities you’d like to use in many components, but you don’t want to pollute the global scope. In these cases, you can make them available to each Vue instance by defining them on the prototype
Vue.prototype.$appName = 'My App'
And prefix these injected properties with '$'...
$ is a convention Vue uses for properties that are available to all instances. This avoids conflicts with any defined data, computed properties, or methods.
If you just want to use the code in your components (pages), you only need to import and use the method:
TestPage.vue
<template>
<div>
<h1>{{ getTest }}</h1>
</div>
</template>
<script>
import test from '~/plugins/helper.js'
export default {
computed: {
getTest () {
return test()
}
}
}
</script>
Hello you can inject the function globally into Vue doing the following:
./plugins/myPluging.js
import Vue from 'vue'
Vue.prototype.$nameOfMyPlugin = (args) => {
// Code here
}
Them in all your components you can access it this way:
./components/myComponent.vue
<script>
export default {
name: 'c',
mounted () {
this.$nameOfMyPlugin('something useful')
}
}
</script>
And that's it :) hope this helps.
-- Reference: https://nuxtjs.org/guide/plugins/#inject-in-root-amp-context
Below is a a custom js plugin that I have used in one of my nuxt projects.
create your file inside the plugins folder, and make your own function as below
export default (context, inject) => {
const formatDate = (dateTime) => {
if (typeof(dateTime) === 'undefined' || dateTime === null) {
return null;
}
let tempDate = new Date(dateTime);
tempDate.setMinutes(tempDate.getMinutes() -
tempDate.getTimezoneOffset());
tempDate = tempDate.toISOString().slice(0, 16);
return tempDate;
}
// Inject $hello(msg) in Vue, context and store.
inject('formatDate', formatDate)
// For Nuxt <= 2.12, also add 👇
context.$formatDate = formatDate
}
Add the plugin to nuxt.config.js and you will be able to use it globally.
myPlugin.js
export default (_, inject) => {
const myFuncA = value => return value;
const myFuncB = value => return myFuncA(1) + value;
inject('myPlugin', { myFuncA, myFuncB }
)
nuxt.config.js
plugins[
'#/plugin/myPlugin.js'
]
myComponent.vue
created(){
console.log( this.$myPlugin.funcA(2) );
}
in myPlugin.js, instead of "_" can use some public nuxt variables like {$config}