• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

武飞扬头像
·某某·
帮助1

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

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbcjje
系列文章
更多 icon
同类精品
更多 icon
继续加载