Solve the problem of nuxt custom global method global attribute and global variable
- 2021-09-12 00:22:34
- OfStack
Note that this is still not available in asyncData, but it can be used in other life cycles such as mounted.
In asyncData, because I can't get this, he executed it before the component initialization. If I find a way, I will continue to update it to the next blog
Ok, now let's go to the steps. Add a new commom. js name to the plugins folder. You can choose your own name
commom. js test code
import Vue from 'vue'
var comsys= {
install(Vue){
Vue.prototype.comsys = {
val:function(val){
return val
}
};
}
}
Vue.use(comsys);
Add in nuxt. config. js
plugins:
[
{ src: '~/plugins/commom.js', ssr: false }
],
Referenced page addition
mounted () {
alert(this.comsys.val(1));
}
Well, that's it ~
This is the instance method. Other attribute objects can refer to the official website of vue
Additional knowledge: The Nuxt project uses global variables, functions, and hybrid
When using the CSS preprocessing language in the Nuxt project, it is very necessary to add variables, functions or mixtures globally, which can be used anywhere in the project. What should I do?
Download @ nuxtjs/style-resources first
npm install @nuxtjs/style-resources
After that, add it in nuxt. config. js
//.......
modules: [
'@nuxtjs/style-resources'
],
styleResources: {
sass: [],
scss: [],
less: [],
stylus: []
}
//.......
For example, if you use stylus preprocessing language, you have an variable. styl variable file under/asset/css, which can be like this
export default {
modules: ['@nuxtjs/style-resources'],
styleResources: {
stylus: './assets/css/variable.styl'
}
}
You can change the path to. /assets/css/global/*. styl if you want to import more than one file globally. Just put the files you want to inject globally in the global directory
Note:
Path aliases such as ~ or @ cannot be used here
Never inject a real style file in this way. This way is only used to inject declarative content such as variables, functions, blends, etc., not real styles; If you do that, you will inject uncontrollable global styles into each component, and you will be confused