Where to store common component methods in #NUXT.JS - javascript

Actually i want to know where to store common components methods in #NUXT.JS.
things which i have tried.
--> Storing common code in middleware (its use-less) because according to my knowledge middleware is only capable of handling request and response to server.
methods: {
// states methods.
SwitchManager: function (__dataContainer, __key, __value) {
// stand alone debugger for this module.
let debug = __debug('computed:_3levelSwitch')
// debug showing function loaded.
debug('(h1:sizeCheck) creating switch..')
// switch.
switch (__key) {
// fake allow set value to true of given key
default:
this[__dataContainer][__key][__value] = true
break
}
return this[__dataContainer][__key][__value]
},
SizeCheck: function (__size) {
// stand alone debugger for this module.
let debug = __debug('tags:p')
// debug showing function loaded.
debug('(p:sizeCheck) checking..')
// init switch.
this.SwitchManager('pill', 'size', __size)
},
StateCheck: function (__state) {
// stand alone debugger for this module.
let debug = __debug('tags:h1')
// debug showing function loaded.
debug('(h1:sizeCheck) checking..')
// init switch.
this.SwitchManager('pill', 'state', __state)
}
},
created () {
// h1 tag size check
this.SizeCheck(this.size)
this.StateCheck(this.state)
}

I go for mixins like with plain vue.js. Only difference - for global mixins - I include them as a plugin, but first:
Non global mixins
I would create an extra folder for my mixins. For example in a /mixins/testMixin.js
export default {
methods: {
aCommonMethod () {}
}
}
Then import in a layout, page or component and add it via the mixins object:
<script>
import commonMixin from '~/mixins/testMixin.js'
export default {
mixins: [commonMixin]
}
</script>
Global mixins
For example in a new file plugins/mixinCommonMethods.js:
import Vue from 'vue'
Vue.mixin({
methods: {
aCommonMethod () {}
}
})
Include that file then in nuxt.config.js
plugins: ['~/plugins/mixinCommonMethods']
After that you would have the method everywhere available and call it there with this.commonMethod(). But here an advice from the vue.js docs:
Use global mixins sparsely and carefully, because it affects every single Vue instance created, including third party components. In most cases, you should only use it for custom option handling like demonstrated in the example above. It’s also a good idea to ship them as Plugins to avoid duplicate application.
Inject in $root & context
Another possibility would be to Inject in $root & context

Related

How to access "this" context (Vue/Nuxt instance) in a VanillaJS file?

I have a function inside a .js file in a nuxt 2 project.
Basically I need to use a nuxt module property from nuxt.config like this this.nuxt.options. inside a function in a normal .js file.
For example:
aNormalJsFile.js
if (this.nuxt.options.module.triggers.isActive) {
// do something
}
But now I can't because it doesn't know what is Nuxt of course. I'm getting this error:
Cannot read properties of undefined (reading 'nuxt')
If you want to inject a Vue/Nuxt instance inside of a .js file (vanilla JS), you can follow this helper function approach
/src/utils/printCoolNumber.js
export const printIt = (VueInstance) => console.log(VueInstance.coolNumber)
// ☝🏻 basically does console.log(this.coolNumber) as in a .vue file
Any .vue file
<script>
import { printIt } from "#/utils/printCoolNumber";
export default {
data() {
return {
coolNumber: 12,
};
},
mounted() {
printIt(this) // 👈🏻 Vue instance ("this") passed here, it prints 12 in the console
},
};
</script>
I wouldn't say that this is the best approach in the long run (using Composables is usually still better) but it is great for small helper functions where you don't need too much Vue-specific methods.

NuxtJS calling hooks from within plugin

Is it possible to use callHook in a custom plugin?
I have to register a custom service class for fetching data and the fastest way to do this was by registering my custom class within a module like this (example taken from this Medium post: https://medium.com/swlh/service-classes-using-plugins-in-nuxt-js-32c0f387ecb9):
// plugins/services.plugin.js
import { LoggingService } from '../logging.service'
export default ({ app }, inject) => {
// create an instance of the LoggingService with the prefix 'My App'
const logging = new LoggingService('My App')
// inject the service, making it available in the context, component, store, etc.
inject('logging', logging)
}
Everything works as expected except I can't for the life of me figure it out if I can define my custom hooks in a plugin. I figured if I can get a reference to the nuxt context I'd be able to do it. I did not find any information about whether what I'm trying to do was possible or not.

Nuxtjs custom module

I'm quite new to Nuxtjs so I made a test project which purpose is merely the (of course) testing of Nuxtjs functionalities.
Currently I'm trying to create a simple custom module: afaik a module is basically a wrapper around a vou/js library/plugin, something like a high-level integration used to expose configurations on how the underlying library/plugin is imported and used in the Nuxt application.
So I'm trying with a simple module that declare some plain js classes that I'll use in my application, e.g. Order and Product, and that's what I came out with:
Directory structure
pages
the-page.vue
modules
classes
index.js
order.js
/modules/classes/index.js
const path = require('path')
export default function (moduleOptions) {
const { nuxt } = this
// add the debug plugin
this.addPlugin({
src: path.resolve(__dirname, 'order.js'),
})
}
/modules/classes/order.js
class Order {
constructor(id) {
this.id = id;
console.log('created order #' + this.id);
}
}
export {Order};
/nuxt.config.js
export default {
// ...
buildModules: [
// ...
'~/modules/classes'
],
// ...
}
/pages/the-page.vue
<script>
export default {
name: 'ThePage',
data () {
return {
}
},
methods: {
createOrder () {
const order = new Order(123)
}
}
}
</script>
The error
My defined class are still not imported in my pages:
/app/pages/the-page.vue
18:13 error 'order' is assigned a value but never used no-unused-vars
18:25 error 'Order' is not defined no-undef
Considerations
Probably I'm missing something about modules usage and/or implementation, but every tutorial I found starts with too complex scenarios, and since I'm at the beginning with Nuxtjs I need something easier to implement.
Ok, I found out that I was mistaken how NuxtJs modules are intended to work and was traying to do somenthing they are not intended for.
Nuxt modules cannot import js classes in every component of the application as I wanted to do, they just "add a property" to the main application instance that is made accessible through this.$<something>, like e.g. you can already do in simple Vue with the Vue Router or the Vuex store plugins that give access to the this.$router and this.$store properties.
NuxtJs modules just wrap simple plugins and expose configuration options to made.

Sharing functions among Vue.js components?

In my application, I have a lot of utility functions that do little things from parsing strings to making toasts and so on. My question is how do I access these in other .vue files? I don't want to rewrite these functions for every new Vue component that I write. Will I be able to use these by importing one component into another? (Vue complains if I don't add the component in the template of another, meaning I can't just import that JavaScript). If so, is that a good/sensible thing to do? What's the standard way to do this?
Mixins is a concept you can try.
import the component which you need.
add mixin array as below in your component just above the data section (or wherever possible)
mixins:[yourimportedcomponent],
data:....
Call the method you want using this.theMethodYouWant();
More you can find it here https://v2.vuejs.org/v2/guide/mixins.html
You could create plugin that exposes the functions on Vue. Plugins documentation
// group utils functions together
Vue.prototype.$utils = {
funcA: function () { ... },
funcB: function () { ... }
}
or
Move them all to common utilities module, src/utils.js, then each Vue component can import as needed:
// src/utils.js
const funcA = () => {
console.log('funcA');
}
const funcB = () => {
console.log('funcB');
}
export { funcA, funcB }
// VueComponentA.vue
import { funcA } from 'path/to/utils';
// VueComponentB.vue
import { funcB } from 'path/to/utils';

How can i set variables that i can access globally throught my app? [duplicate]

I initialized i18n translation object once in a component (a first component that loads in the app ). That same object is required In all other components. I don't want to re-initialize it in every component. What's the way around? Making it available to window scope doesn't help as I need to use it in the render() method.
Please suggest a generic solution for these problems and not i18n specific solution.
Beyond React
You might not be aware that an import is global already. If you export an object (singleton) it is then globally accessible as an import statement and it can also be modified globally.
If you want to initialize something globally but ensure its only modified once, you can use this singleton approach that initially has modifiable properties but then you can use Object.freeze after its first use to ensure its immutable in your init scenario.
const myInitObject = {}
export default myInitObject
then in your init method referencing it:
import myInitObject from './myInitObject'
myInitObject.someProp = 'i am about to get cold'
Object.freeze(myInitObject)
The myInitObject will still be global as it can be referenced anywhere as an import but will remain frozen and throw if anyone attempts to modify it.
Example of react state using singleton
https://codesandbox.io/s/adoring-architecture-ru3vt
(see UserContext.tsx)
If using react-create-app
(what I was looking for actually) In this scenario you can also initialize global objects cleanly when referencing environment variables.
Creating a .env file at the root of your project with prefixed REACT_APP_ variables inside does quite nicely. You can reference within your JS and JSX process.env.REACT_APP_SOME_VAR as you need AND it's immutable by design.
This avoids having to set window.myVar = %REACT_APP_MY_VAR% in HTML.
See more useful details about this from Facebook directly:
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
Why don't you try using Context?
You can declare a global context variable in any of the parent components and this variable will be accessible across the component tree by this.context.varname. You only have to specify childContextTypes and getChildContext in the parent component and thereafter you can use/modify this from any component by just specifying contextTypes in the child component.
However, please take a note of this as mentioned in docs:
Just as global variables are best avoided when writing clear code, you should avoid using context in most cases. In particular, think twice before using it to "save typing" and using it instead of passing explicit props.
Create a file named "config.js" in ./src folder with this content:
module.exports = global.config = {
i18n: {
welcome: {
en: "Welcome",
fa: "خوش آمدید"
}
// rest of your translation object
}
// other global config variables you wish
};
In your main file "index.js" put this line:
import './config';
Everywhere you need your object use this:
global.config.i18n.welcome.en
Is not recommended but.... you can use componentWillMount from your app class to add your global variables trough it... a bit like so:
componentWillMount: function () {
window.MyVars = {
ajax: require('../helpers/ajax.jsx'),
utils: require('../helpers/utils.jsx')
};
}
still consider this a hack... but it will get your job done
btw componentWillMount executes once before rendering, see more here:
https://reactjs.org/docs/react-component.html#mounting-componentwillmount
Here is a modern approach, using globalThis, we took for our React Native app.
globalThis is now included in...
Modern browsers - MDN documentation
Typescript 3.4 - Handbook documentation
ESLint v7 - Release notes
appGlobals.ts
// define our parent property accessible via globalThis. Also apply the TypeScript type.
var app: globalAppVariables;
// define the child properties and their types.
type globalAppVariables = {
messageLimit: number;
// more can go here.
};
// set the values.
globalThis.app = {
messageLimit: 10,
// more can go here.
};
// Freeze so these can only be defined in this file.
Object.freeze(globalThis.app);
App.tsx (our main entry point file)
import './appGlobals'
// other code
anyWhereElseInTheApp.tsx
const chatGroupQuery = useQuery(GET_CHAT_GROUP_WITH_MESSAGES_BY_ID, {
variables: {
chatGroupId,
currentUserId: me.id,
messageLimit: globalThis.app.messageLimit, // 👈 used here.
},
});
Can keep global variables in webpack i.e. in webpack.config.js
externals: {
'config': JSON.stringify({ GLOBAL_VARIABLE: "global var value" })
}
In js module can read like
var config = require('config')
var GLOBAL_VARIABLE = config.GLOBAL_VARIABLE
Hope this will help.
The best way I have found so far is to use React Context but to isolate it inside a high order provider component.
Maybe it's using a sledge-hammer to crack a nut, but using environment variables (with Dotenv https://www.npmjs.com/package/dotenv) you can also provide values throughout your React app. And that without any overhead code where they are used.
I came here because I found that some of the variables defined in my env files where static throughout the different envs, so I searched for a way to move them out of the env files. But honestly I don't like any of the alternatives I found here. I don't want to set up and use a context everytime I need those values.
I am not experienced when it comes to environments, so please, if there is a downside to this approach, let me know.
Create a file :
import React from "react";
const AppContext = {};
export default AppContext;
then in App.js, update the value
import AppContext from './AppContext';
AppContext.username = uname.value;
Now if you want the username to be used in another screen:
import AppContext from './AppContext';
AppContext.username to be used for accessing it.
For only declaring something, try this. Make sure MyObj is assigned at the proper time for you want to access it in render(), many ways was published before this thread. Maybe one of the simplest ways if undefined then create it does the job.
declare global {
interface Window {
MyObj: any;
}
}
USE CUSTOM HOOKS
It is very simple if you use custom hooks
Refer this link
https://stackoverflow.com/a/73678597/19969598
Full sample usage is available in the above post
This answer is for global part of question not I18N.
I wanted a global variable and function across all components of my application and without child-parent relationship.
This Answer is like a good one; but it was not completely clear to me so i had to test it my way.
I used below approach; not sure if this is a "good or bad practice" or even "off-topic"; but share in case help someone.
Global.jsx
const Global = () => { }
export default Global;
Global.var = 100;
Global.func = () => {
Global.var += 1;
alert(Global.var);
}
MyComponent1.jsx
import Global from "./Global";
import React from "react";
const MyComponent1 = () => {
return ( <h1 onClick={Global.func}>COM1: {Global.var}</h1>)
}
export default MyComponent1;
MyComponent2.jsx
import Global from "./Global";
import React from "react";
const MyComponent2 = () => {
return ( <h1 onClick={Global.func}>COM2: {Global.var}</h1>)
}
export default MyComponent2;
And anywhere like index.js
root.render(
<div>
.
.
.
<MyComponent1/>
<MyComponent1/>
<MyComponent2/>
<MyComponent2/>
.
.
.
</div>
);
Note: This way you have access to a global function or variable; but provided sample cannot update (render) screen itself cause no state or prop has been changed.
We can change the solution like this and keep ref of our components or DOM objects in our Global Zone like this (Not that i do not know its a good practice or even the worst case; so its on your own):
Global.jsx
const Global = () => { }
export default Global;
Global.var = 100;
Global.refs = [];
Global.inc = () => {
Global.var += 1;
Global.refs.forEach(ref => {
ref.current.innerText = Global.var;
});
}
MyComponent1.jsx, MyComponent2.jsx, ...
import Global from "./Global";
import React, { createRef } from "react";
const MyComponent1 = () => {
const ref = createRef();
Global.refs.push(ref);
return (<div onClick={Global.inc}>
<h2>COM1:</h2>
<h3 ref={ref} >{Global.var}</h3>
</div>);
};
export default MyComponent1;
I don't know what they're trying to say with this "React Context" stuff - they're talking Greek, to me, but here's how I did it:
Carrying values between functions, on the same page
In your constructor, bind your setter:
this.setSomeVariable = this.setSomeVariable.bind(this);
Then declare a function just below your constructor:
setSomeVariable(propertyTextToAdd) {
this.setState({
myProperty: propertyTextToAdd
});
}
When you want to set it, call this.setSomeVariable("some value");
(You might even be able to get away with this.state.myProperty = "some value";)
When you want to get it, call var myProp = this.state.myProperty;
Using alert(myProp); should give you some value .
Extra scaffolding method to carry values across pages/components
You can assign a model to this (technically this.stores), so you can then reference it with this.state:
import Reflux from 'reflux'
import Actions from '~/actions/actions'
class YourForm extends Reflux.Store
{
constructor()
{
super();
this.state = {
someGlobalVariable: '',
};
this.listenables = Actions;
this.baseState = {
someGlobalVariable: '',
};
}
onUpdateFields(name, value) {
this.setState({
[name]: value,
});
}
onResetFields() {
this.setState({
someGlobalVariable: '',
});
}
}
const reqformdata = new YourForm
export default reqformdata
Save this to a folder called stores as yourForm.jsx.
Then you can do this in another page:
import React from 'react'
import Reflux from 'reflux'
import {Form} from 'reactstrap'
import YourForm from '~/stores/yourForm.jsx'
Reflux.defineReact(React)
class SomePage extends Reflux.Component {
constructor(props) {
super(props);
this.state = {
someLocalVariable: '',
}
this.stores = [
YourForm,
]
}
render() {
const myVar = this.state.someGlobalVariable;
return (
<Form>
<div>{myVar}</div>
</Form>
)
}
}
export default SomePage
If you had set this.state.someGlobalVariable in another component using a function like:
setSomeVariable(propertyTextToAdd) {
this.setState({
myGlobalVariable: propertyTextToAdd
});
}
that you bind in the constructor with:
this.setSomeVariable = this.setSomeVariable.bind(this);
the value in propertyTextToAdd would be displayed in SomePage using the code shown above.

Categories