Vue3相关知识 | 青训营笔记

128 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 1 天。

Vue3动态绑定class类名

select选择器组件开发部分知识点

以对象的形式

:class="{'类名': 布尔值, '类名': 布尔值, ...}"

<li :class="{'is-disable': isDisabled}">以对象的形式动态添加类名</li>
<li :class="{'is-disable': isDisabled, 'selected': isSelected}">以对象的形式动态添加类名</li>

以三元表达式的形式

:class="[ 表达式 ? 'className1' : 'className2']"

<p :class="[ 1 < 2 ? 'className1' : 'className2' ]" >三元表示式(文字的颜色)</p>

以数组的形式

:class="[变量1, 变量2, ...]"
可以直接为直接定义的变量,或者为computed计算得到的变量,或者为可以返回字符串的函数

<template>
    <byte-button :class="[typeClass, plainClass]">数组的形式(文字的颜色)</byte-button>
</template>
<script setup>
import {computed} from "vue";
const typeClass = props.type === undefined ? "" : "byte-button-" + props.type;
const plainClass = computed(() => {
    if (props.plain) {
        return "is-plain";
    }
})
</script>

Vue3获取的attrs和slots

通过调用vue中的useAttrs, useSlots来获取context中的内容
attrs存储传递给子组件,但未被子组件props接收的属性

<script setup> 
    import { useAttrs, useSlots } from "vue"; 
    const attrs = useAttrs(); 
    const slots = useSlots(); 
</script>

getCurrentInstance()

参考链接

import {getCurrentInstance} from "vue";

// 获取当前组件实例
const instance = getCurrentInstance();

// 获取当前组件的上下文,下面两种都能获取到数组的上下文
// 方式一:开发环境中才可以使用
const {ctx} = getCurrentInstance();
// 方式二:开发环境和生产环境都能用,推荐!!!
const {proxy} = getCurrentInstance();

// ctx 中包含了组件中由ref和reactive创建的响应式数据对象,以及以下对象及方法;
proxy.$attrs
proxy.$data
proxy.$el
proxy.$emit
proxy.$forceUpdate
proxy.$nextTick
proxy.$options
proxy.$parent
proxy.$props
proxy.$refs
proxy.$root
proxy.$slots
proxy.$watch

v-bind() CSS变量注入

在script标签中定义变量,

  • 若是普通定义的变量,v-bind(变量)
  • 若是ref定义的响应式变量,v-bind(变量)
  • 若是reactive定义的响应式变量,v-bind("响应式变量.某一个变量")
  • props接收的变量,v-bind(props.某一变量)
<template> 
    <span>Jerry</span> 
</template> 
<script setup> 
    import { ref, reactive } from "vue"; 
    // prop接收样式 
    const props = defineProps({ 
        border: { 
            type: String, 
            default: "1px solid yellow"
        } 
    }); 
    // 常量声明样式 
    const background = "red"; 
    // 响应式数据声明样式 
    const color = ref("blue"); 
    const style = reactive({ opacity: "0.8" }); 
</script> 
<style lang="scss" scoped> 
span { 
    // 使用常量声明的样式 
    background: v-bind(background); 

    // 使用响应式数据声明的样式 
    color: v-bind(color); 
    opacity: v-bind("style.opacity"); 

    // 使用prop接收的样式 
    border: v-bind("props.border"); 
} 
</style>

动态组件component

vue提供了一个内置的<component> ,专门用来实现动态组件的渲染。
这个标签就相当于一个占位符,需要使用is属性指定绑定的组件
传递组件属性

<template>
    <byte-button type="primary" :icon="Edit" />
</template>
<script setup>
import { Edit } from '@element-plus/icons-vue'
</script>

接收并使用
icon是props中接收的属性

<component :is="icon"/>