vueuse笔记-Component

406 阅读1分钟

computedInject

把computed和inject的功能组合起来,用于对注入的数据进行响应式计算
示例如下:
context.js

import  { InjectionKey } from "vue";
interface Item{
  key:number,
  value:string
}
export const ArrayKey:InjectionKey<Item[]> = Symbol('symbol-key')

father.vue

<template>
<child/>
</template>
<script setup>
import {ref,provide} from 'vue'
import {ArrayKey} from './context'
import child from './child'
const array = ref([
{
 key:1,
 value:'苹果'
},
{
 key:2,
 value:'香蕉'
}
])
provide(ArrayKey,array)
</script>

children.vue

<template>
{{computedArray}}
</template>
<script setup>
import {ArrayKey} from './context'
import {computedInject} from '@vueuse/core'
const computedArray = computedInject(ArrayKey,source=>{
    const arr = [...source.value]
    arr.unshift({
        key:0,
        value:'水果'
    })
    return arr
})
</script>

最终结果: 在father.vue页面上显示 [ { key:0, value:'水果' }, { key:1, value:'苹果' }, { key:2, value:'香蕉' } ]

createReusableTemplate

在组件范围内定义和重用模板
示例如下:

<template>
  <div class="">
    <DefineTemplate>
        <child></child>
    </DefineTemplate>
    <a-modal v-model:visible="showDialog">
      <ReuseTemplate/>
    </a-modal>
    <div>
      <ReuseTemplate/>
    </div>
    <a-button @click="changeDialog()">切换显示模态框{{showDialog}}</a-button>
  </div>
</template>
<script setup>
import {ref} from 'vue'
import {createReusableTemplate} from '@vueuse/core' 
const [DefineTemplate,ReuseTemplate] = createReusableTemplate();
const showDialog = ref(false);
function changeDialog(){
  showDialog.value = !showDialog.value
}
</script>

unrefElement

解绑dom元素的ref响应性
用法示例:

<template>
  <div ref="div"/>
  <HelloWorld ref="hello"/>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { unrefElement } from '@vueuse/core'

const div = ref() // will be bind to the <div> element
const hello = ref() // will be bind to the HelloWorld Component

onMounted(() => {
  console.log(unrefElement(div)) //打印结果是div元素: <div></div>
  console.log(unrefElement(hello)) // the root element of the HelloWorld Component
})
</script>

useMounted

以ref的数据格式显示mounted 状态
用法如下:

import { useMounted } from '@vueuse/core'
const isMounted = useMounted()

对等于

const isMounted = ref(false)
onMounted(() => {
  isMounted.value = true
})

useVModel

为组件创建自定义 v-model 的绑定, 组件接受 props 和 propName, 当该值被修改时, 组件会向父级发出更新事件, 即 props + emit -> ref
用法示例: father.vue中

<template>
 <div>
   <child :msg="data" @update:msg="updateMsg"/>
 </div>
</template>
<script setup>
import {ref} from 'vue'
let msg = '这是一条信息'
 function updateMsg(newMsg){
  msg.value = newMsg
 }
</script>

child.vue中

<template>
 <a-button @click="changeProps()"></a-button>
</template>
<script lang="ts" setup>
import { useVModel,useVModels } from '@vueuse/core'
const props = defineProps<{
  msg: string
}>()
const emit = defineEmits(['update:msg'])
const msg = useVModel(props, 'msg', emit)// 可以写为:const {msg} = useVModels(props, emit)
function changeMsg(){
    msg.value = '这是修改后的信息'
}
</script>