vue3笔记十四(vue3自定义全局函数及变量、css新特性)
vue3中没有Prototype属性,使用app.config.globalProperties去替代
·
1、globalProperties
vue3中没有Prototype属性,使用app.config.globalProperties去替代
// vue2中
Vue.prototype.$message = '全局变量'
// vue3中
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
app.config.globalProperties.$val = '我是全局变量'
2、全局函数及变量
// 定义
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// 全局函数, 获取数组首项某个值
app.config.globalProperties.$firstValue = (arr: any[], key:string, val = undefined):any => {
if (arr.length !== 0) {
if (typeof arr[0] === 'object') {
return arr[0][key]
} else {
return arr[0]
}
} else {
return val
}
}
app.config.globalProperties.$val = '我是全局变量'
app.mount('#app')
// 界面使用----------------------------------------------------------------------------
<template>
<button @click="change">change</button>
</template>
<script setup lang="ts">
import { getCurrentInstance } from "vue";
const {appContext} = getCurrentInstance()
const arr = [
{id: 1, name: '苹果'},
{id: 2, name: '香蕉'},
{id: 3, name: '葡萄'},
{id: 4, name: '恐龙'},
]
const change = () => {
const name = appContext?.config?.globalProperties?.$firstValue(arr, 'name')
const val = appContext?.config?.globalProperties?.$val
console.log('------', name, val)
}
</script>
3、css新特性
// 根组件
<template>
<div>根组件</div>
<A>
<div class="aaa">aaa的插槽</div>
</A>
<el-input style="width: 200px;" class="ipt"></el-input>
</template>
<script setup lang="ts">
import A from './A.vue'
</script>
<style scoped lang="less">
.ipt {
// 1、深度选择器
:deep(.el-input__wrapper) {
background-color: skyblue;
}
}
</style>
// 插槽组件------------------------------------------------------------------------------------------
<template>
<div>
<h1>aaa组件</h1>
<slot></slot>
</div>
<div class="wrap">
aaa内容
</div>
</template>
<script setup lang="ts">
const color = ref<string>('red')
const obj = ref({
width: '200px'
})
</script>
<style scoped>
// 2、插槽选择器
:slotted(.aaa) {
color: red;
}
// 3、全局选择器
:global(div) {
background-color: skyblue;
}
.wrap {
// 4、动态css, 如果是对象v-bind加引号
width: v-bind('obj.width');
background-color: v-bind(color);
}
</style>
原文链接:
https://xiaoman.blog.csdn.net/article/details/123292042
https://xiaoman.blog.csdn.net/article/details/124754590
更多推荐
已为社区贡献8条内容
所有评论(0)