【vue3】小技巧合集

1. v-bind 样式绑定变量

<template>
  <div class="text">hello</div>
</template>

<script setup lang="ts">
const color = ref('red');
</script>

<style>
  .text {
    
    
    color: v-bind (color);
  }
</style>

2. 传送门teleport

to 挂载在哪里,放在盒子的内部最后面

<div>
    <button>确定</button>
    <teleport to="body"> 
      <div>
        弹窗
      </div>
    </teleport>
  </div>

3. watch监听多个ref数据变化 / 监听props数据

const test1 = ref('0')
const test2 = ref('1')
watch([()=>test1,()=>test2],(newValue, old) => {
    
     
   //监听多个数据,以数组的形式就行,返回的新旧值也是以数组的形式返回
       console.log(newValue,old)
 });

如果我们想侦听 props 上的属性变化:

// 假设 props 上有个 data属性
// 下面的写法会生效
watch(
  () => props.data,
  (val, preVal) => {
    
    
    /* ... */
  }
)

// 下面的写法不会被触发
watch(props.data, (val, preVal) => {
    
    
  /* ... */
})

4.provide,inject 定义变量全局使用

        provide跟react 中的提供者相似 用来提供数据,一般用在入口文件
        inject就类似于消费者,用来取用数据,哪里用哪里引用,这里举个例子eleplus的全局消息提示框。
        也可以进行不同组件的数据传递
        首先在main.js中定义文件
        provide provide(‘注入的属性名’,‘注入的属性值’)可以使用ref(‘注入的属性值’)这样可以动态绑定渲染
        inject inject(‘接收的属性名跟注入的一致’)

import {
    
    ElMessage} from 'element-plus' //引入提示框
app.use(ElementPlus)//如果没有在全局引用的话就需要在原型上面添加
//app.config.globalProperties.$message = ElMessage;
app.provide('$message', ElMessage) //定义好数据接下来就是在需要用的文件中引入就行
import {
    
    inject,onBeforeMount} from 'vue'
 onBeforeMount(() => {
    
    
     	inject($message).success('注册成功')   //直接写在生命周期中有效
    });
//下面是没有定义写在非生命周期的方法中,
//注意此时引入inject一定还要在下面定义不然就回报错
 const btnClick=()=>{
    
    
	inject($message).success('注册成功') //这里会报错看下图
}
//定义之后的代码,不会报错
const $message=inject("$message")
onBeforeMount(() => {
    
    
     	$message.success('注册成功') 
 });
const btnClick=()=>{
    
    
	$message.success('注册成功')
}

5. Suspense组件

        Suspense组件用于在等待某个异步组件解析时显示加载中或其他内容。
        它提供了两个插槽:default,fallback,刚开始会渲染一个 fallback 状态下的内容, 直到到达某个条件后才会渲染 default 状态的正式内容, 通过使用 Suspense 组件进行展示异步渲染就更加的简单。

<Suspense>
      <template #default>
	  		<!-- 异步渲染 -->
	       	...  
      </template>
      <template #fallback>
          <div>
              Loading...
          </div>
      </template>
</Suspense>

6. vue3里用this

方法一

import {
    
     getCurrentInstance, ComponentInternalInstance } from 'vue';

const instance = getCurrentInstance()
const _this= instance.appContext.config.globalProperties
console.log(_this);

方法二

import {
    
     getCurrentInstance, ComponentInternalInstance } from 'vue';

const {
    
     proxy } = getCurrentInstance()
console.log(proxy );

猜你喜欢

转载自blog.csdn.net/qq_38974163/article/details/122828449