I am using Vue.js
but with simply JS
files and not vue
files and I am importing a component into my main app.js
like so:
import autoPosts from './components/autoPosts.js';
It imports it just fine, but I am trying to access these globals. Before people destroy me for using global variables, can you just tell me if this is possible.
const apiRoot = location.origin + '/wp-json/wp/v2/';
const acfApiRoot = location.origin + '/wp-json/acf/v3/';
import autoPosts from './components/autoPosts.js';
It doesn't read apiRoot
or acfApiRoot
within that component whether I include it before or after the variables.
The only way it works is if I declare the variables inside my component file autoPosts.js
Just because app.js
is the main module doesn't mean that variables declared in it become global. But you should not use global variables anyway. Instead, create another module
// config.js
export const apiRoot = location.origin + '/wp-json/wp/v2/';
export const acfApiRoot = location.origin + '/wp-json/acf/v3/';
that you can import where you need the constants:
// components/autoPosts.js
import { apiRoot, acfApiRoot } from '/config.js';
…
just using
const apiRoot = 'whatever';
doesn't make it a global variable and is not accesible since it isn't exported.
To use a global variable, add it to window;
window.apiRoot = 'whatever';
and it will be accessible from any other classes with simple the variable name
console.log(apiRoot); // outputs 'whatever'
Can it not use window?
window.apiRoot = location.origin + '/wp-json/wp/v2/';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With