2022-03-03 vue3中使用全局变量
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2022-03-03 vue3中使用全局变量相关的知识,希望对你有一定的参考价值。
参考技术A 对比:在vue2.x中我们挂载全局变量或方法是通过是使用 Vue.prototype.$api=xxx 的形式来挂载,然后通过 this.$xxx 来获取挂载到全局的变量或者方法
但是 在vue3.x中显然是不行滴,在setup里面我们都获取不到this,但是 别怕 vue3.x官网给我们提供了新的方法 叫: globalProperties 。添加一个可以在应用的任何组件实例中访问的全局 property 。组件的 property 在命名冲突具有优先权
用法: 比如我们挂在一下我们的axios
在main.ts上
在我们页面上引用:
Vue-cli中使用scss 的全局变量和 @mixin
安装 scss
npm install sass-loader@10.1.1 --save-dev
npm install node-sass --sava-dev
注意:sass-loader需要指定@10的版本,因为后续的版本在vue-cli脚手架中会出现一些问题
基础使用
<style lang="scss" scoped>
.xxxx {
.xxx-x {
...
}
}
</style>
大部分场景下,使用scss可以实现上面的样式嵌套层级关系,相信大家都用过。
下面要说下scss的进阶用法。scss 全局变量和mixin。
环境配置
想要在vue-cli中全局使用 scss的全局变量和 @mixin样式混入,需要安装插件,然后在 vue.conf.js
中配置
npm install style-resources-loader vue-cli-plugin-style-resources-loader --save-dev
vue.config.js
中配置
module.exports = {
pluginOptions: {
\'style-resources-loader\': {
preProcessor: \'scss\',
patterns: [
// 路径根据具体需求更改
path.resolve(__dirname, \'src/assets/styles/variables.scss\'),
path.resolve(__dirname, \'src/assets/styles/mixin.scss\')
]
}
}
}
scss全局变量的使用
上述环境配置中配置的 variables.scss
就是全局的变量文件
variables.scss
$--color-primary: #468fff;
$--color-primary-active: #69a5ff;
xxx.vue
文件中直接使用该变量
<style lang="scss" scoped>
.main-wrap {
background: $--color-primary;
}
</style>
@mixin与@include实现css编程式风格
mixin.scss
@mixin 函数名($参数名: 默认值)
@mixin flex($justify-content: center, $align-center: center, $flex-direction: row){
display: flex;
justify-content: $justify-content;
align-items: $align-center;
flex-direction: $flex-direction;
}
xxx.vue
中使用使用 @include 进行引用即可
<style lang="scss" scoped>
.main-wrap {
@include flex(center,center,row);
}
</style>
以上是关于2022-03-03 vue3中使用全局变量的主要内容,如果未能解决你的问题,请参考以下文章