Answer the question
In order to leave comments, you need to log in
Where is the right place to store data in nuxt?
Help, please, to understand.
I am not very strong in the front-end, in recent years I have hardly followed the development of all these technologies.
I made sites on vuejs, and recently I needed to do it on nuxt.
Where is it correct to store global constants, such as BASE_URL, IMG_URL, etc. I myself found recommendations that you need to store such data in the nuxt.config.js file in the env property and access it through process.env. Here is my question. What is this process? As I understand it, there is such an object in nodejs, but where does it come from on the client? Why can’t it be accessed from the markup, but from the code you can, for example:
//Работать не будет
<img :src="process.env.IMG_URL + '/user-pic.jpg'">
//Работать будет
<img :src="userPicImage">
...
computed {
userPicImage() {
return process.env.IMG_URL + '/user-pic.jpg';
}
}
Answer the question
In order to leave comments, you need to log in
Process.env gets to the browser side via webpack, Alexander Kositsyn correctly described it in general. In nuxt, this plugin is already configured.
You can't from markup because markup runs in its own context (for example, console.log can't be called either). The solution in the forehead is to forward into the markup through data() {}
. A more sustainable solution is to make a nuxt plugin that will inject this data into the vue prototype. For example, like this:
// plugins/nuxt-env-plugin.js
import Vue from 'vue';
Vue.use({
install(Vue) {
Vue.prototype.$env = {IMG_URL: process.env.IMG_URL}; // Vue.prototype.$env = process.env не сработает
},
});
// не забудьте подключить его в nuxt.config.js
<img :src="$env.IMG_URL + '/user-pic.jpg'">
. Just be careful not to pass the entire process.env to the client, because a potential attacker can use environment variables to organize an attack.
process.env is a node variable, yes.
when assembled by webpack, it is converted to a string
https://webpack.js.org/plugins/environment-plugin/
here you can see it. there you need a plugin for webpack to transpile this code.
He may not see this variable in the string, but if the code sees
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question