0
点赞
收藏
分享

微信扫一扫

浅谈Vue开发

吓死我了_1799 2024-06-18 阅读 4

自定义组件某个模块

- vue中可以采用slot即插槽的方式去植入我们自定义的模块

  • 默认插槽

父级:

<MyInput>
    <div>hello 大刷币</div>
</MyInput>



子级:

<div>
<slot></slot>
</div>

  • 具名插槽

父级:

<MyInput>
  <template #handsome>
    <div>hello 大刷币</div>
  </template>
</MyInput>



子级:

<div>
<slot name='handsome'></slot>
</div>

  • 作用域插槽

父级:

<MyInput>
  <template v-slot="{greet}">
    <div>{{greet}}</div>
  </template>
</MyInput>



子级:

<div>
<slot greet="hello 大帅比"></slot>
</div>

挂载到某个节点

<Teleport to="xx"></Teleport>

巧用$attrs

在props和emits显示声明的属性除外,多节点一定要指定不然会有警告~

<template>
<div>hello</div>
<div v-bind="$attrs">大帅比</div>
</template>

defineModel (Vue 3.4)

实现属性双向数据绑定

父组件:
const greet= ref('Hello 大帅比')

<MyInput v-model="greet"></MyInput>

子组件:
<template>
    <div>{{ name }}</div>
</template>
<script setup>
const name = defineModel()
</script>

defineProps/defineEmits

  • defineProps:接受组件的props
  • defineEmits:接受自定义事件
  • defineProps示例,defineEmits类似换个名字即可

<script setup>
//第一种
defineProps(['name', 'age'])
//第二种
defineProps({
    name: {
        type: String,
        default: "大帅比"
    }
})
//第三种
interface Type {
    name: string
}
defineProps<Type>()
</script>

defineExpose

导出组件内的变量和函数,在外层使用ref调用即可

父组件:
const myRef = ref()
<MyInput ref="myRef"></MyInput>

子组件:
<script setup>
defineExpose({
    handleBat,
    name,
    age
})
</script>

toRefs使用场景

  • 使用pinia管理全局状态,内部组件使用store可以解构出来,并套上toRefs可以保持响应式

watchEffect和watch的用法

watchEffect

  • 立即执行
  • 多个依赖的话没办法确认是那个依赖导致的更新
  • 没法获取到依赖的前后更新的值

//基本用法
watchEffect(()=>{
xxxxx
})

//延迟到组件渲染之后执行
watchEffect(()=>{},{flush:'post'})

//依赖改变立即触发
watchEffect(()=>{},{flush:'sync'})

//清除监听
const stop = watchEffect(()=>{
xxxx
})

stop()

watch

  • 懒加载
  • 明确那个依赖导致的更新
  • 可以获取到依赖的更新前后的值

//单个依赖
watch(yy,(new,old)=>{
xxx

})

//多个依赖
watch([x,y],([newX,newY],[oldX,oldY])=>{})

//深度监听
watch(()=>x,(newX,oldX)=>{},{deep:true})
或
watch(x,(newX,oldX)=>{})

//清除监听

const stop= watch(x,()=>{})
stop()

探索生命周期函数 

- 父子生命周期执行顺序

  • 挂载

浅谈Vue开发_Vue


  • 更新

浅谈Vue开发_Vue_02


  • 卸载


浅谈Vue开发_Vue_03

实现一个简易的Toast

import { createVNode, render } from "vue";
import Message from './message.vue'
const ToastFn = () => {
  const container = document.createElement("div");
  return {
    open: function ({...res}) {
        createVNode(Message,{...res})
        render(vNode,container)
    },
    destroy: function () {
        render(null, container);
    }
  };
};
const Toast = ToastFn()
export default Toast

Message.vue:

<template>
    <div>{{ name }}</div>
</template>
<script setup>

defineProps({
    name: {
        type: String,
        default: "大帅比"
    }
})
</script>

举报

相关推荐

0 条评论