学习vue3 八 全局函数和变量,编写插件,scoped,样式穿透,vue3新增的css特性

目录

Vue3定义全局函数和变量

vue3编写插件

scoped和样式穿透

scoped的原理

1. 插槽选择器

2. 全局选择器

3. 动态css

4. css module


Vue3定义全局函数和变量

因为vue3没有prototype属性所以要使用 app.config.globalProperties 来在全局绑定函数或者变量

vue2的用法
Vue.prototype.$http = () => {}

vue3的用法

在main.ts内

import { createApp } from 'vue'
import App from './App.vue'
import "animate.css"

const app = createApp(App)

type Filter = {
     format: (str:string)=>string   
}

declare module 'vue' {
    export interface ComponentCustomProperties {
        $filters: Filter,
        $api: string
    }
}


app.config.globalProperties.$api = "https://api.themoviedb.org/3"
app.config.globalProperties.$filtter = {
    format: (str:string):string=> {
        return '加上' + str
    }
}
app.mount('#app')

需要声明文件declare module 在组件中使用时,才会有提示

在组件中使用,模板中直接插值语法,setup中需要使用getCurrentInstance获取当前实例,然后通过当前实例的props属性找到

<script setup lang="ts">
import { ref } from 'vue';
import {getCurrentInstance} from "vue";
const instance = getCurrentInstance();
const text = ref('');
function changeInput() {
  text.value = instance?.proxy?.$filters.format(text.value) as string;
}
</script>

<template>
  <div class="context">
    <p>{
  {$api}}</p>
    <input type="text" v-model="text" @input="changeInput">
    {
  {text}}
  </div>
</template>

<style scoped>
.image img{
  width: 300px;
}
</style>

vue3编写插件

在使用 createApp() 初始化 Vue 应用程序后,你可以通过调用 use() 方法将插件添加到你的应用程序中。

实现一个Loading

app.vue

<script setup lang="ts">
import {getCurrentInstance} from "vue";
const instance = getCurrentInstance()
instance?.proxy?.$loading.sho
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值