vue3的个人理解

本文目的是记录使用vue3的时候的一些属性的个人理解。

一、defineExpose
  1. 官方说明
    在这里插入图片描述
  2. 个人理解
    <script setup>组件中,defineExpose可以暴露出组件的属性。
  3. 项目实战
    // dialog组件
    <script setup>
    	import { ref } from 'vue'
    	import { Close } from '@element-plus/icons-vue'
    	// dialog 是否可见
    	const dialogVisible = ref(false)
    	// 配置
    	const config = ref({})
    	// 回调
    	let callBack = null
    	
    	// 组件暴露出的方法和属性
    	defineExpose({
    	  openDialog(_config) {
    	    config.value = _config
    	    config.value.id = _config.id
    	    config.value.width = _config.width || '50%' // 默认宽度50%,允许自定义宽度
    	    callBack = _config.callback
    	    dialogVisible.value = true
    	  },
    	})
    	
    	</script>
    	<template>
    	  <el-dialog
    	    v-model="dialogVisible"
    	    align-center
    	    class="i-dialog"
    	    :show-close="false"
    	    :append-to-body="true"
    	    :width="config.width"
    	  >
    	  </el-dialog>
    	</template>
    
    	// 父页面
    	const dialog = ref()
    	
    	function handleStopApi(id) {
    	  dialog.value.openDialog({
    	    width: '480',
    	    title: '您确认要停用该企业吗?',
    	    message: '停用后该企业无法再次登录系统!',
    	    confirmText: '停用',
    	    callback: () => {
    	      disableOrg(id)
    	    },
    	    id,
    	  })
    	}
    	
    	<templete>
    	    <Dialog ref="dialog" />
    	</templete>
    
二、自定义指令
  1. 官方说明
    在这里插入图片描述
  2. 个人理解
    自定义指令,写好自定义指令后,注册指令,页面中通过v-***调用
  3. 项目实战
// src\directives\throttle.js
import throttle from 'lodash/throttle';

export default function throttleDirective() {
  return {
    fn: null,
    mounted(el, binding) {
      const handler = Array.isArray(value) ? value[0] : value;
      const delay = Array.isArray(value) ? value[1] : 1000; // Default delay to 1000 ms if not provided
      const handleThrottle = throttle(handler, delay);
      el.addEventListener(arg, handleThrottle);
    },
  };
}

// main.js
import throttleDirective from '@/directives/throttle.js'

app.directive('throttle', throttleDirective())

// 使用自定义组件
<template>
  <button v-throttle:click="[handleClick, 2000]">Click Me</button>
  <button v-throttle:click="handleClick">Click Me</button>
</template>

<script>
export default {
  methods: {
    handleClick() {
      console.log('Button clicked!');
    },
  },
};
</script>

defineModel
  1. 官方说明
    在这里插入图片描述
  2. 个人理解
    父子组件双向数据绑定使用defineModel, 比以前的写法更加便捷
	<!-- Child.vue -->
	<script setup>
	const props = defineProps(['modelValue'])
	const emit = defineEmits(['update:modelValue'])
	</script>
	
	<template>
	  <input
	    :value="props.modelValue"
	    @input="emit('update:modelValue', $event.target.value)"
	  />
	</template>
  • 6
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值