vue3笔记十四(vue3自定义全局函数及变量、css新特性)

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

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值