关于前端:Vue3x项目开发常用知识点

PS:以下知识点都是基于 vue3.x + typescript + element-plus + setup语法糖 应用的。

一、定义组件属性

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

console.log(props.visible)

[warning] 留神:defineProps 不必从vue引入,setup 语法糖环境会自动识别

二、formatter简写

el-table-column 中应用 formatter 简写

<el-table-column label="工夫" prop="createTime" :formatter="(...args: any[]) => formatTime(args[2])" />

三、子父组件通信

子组件:

<script setup lang="ts">
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['closeILdialog']) // 注册触发器,defineEmits不必从vue引入,setup语法糖环境会自动识别
function onDialogClose() {
  emit('closeILdialog') // 触发
}
</script>

<template>
<el-dialog
    v-model="visible"
    width="900px"
    @close="onDialogClose"
    title="日志"
    :close-on-click-modal="false"
  >
  </el-dialog>
</template>

父组件:

<script setup lang="ts">
let ILdialog = reactive({
  visible: false
})
function closeILdialog() {
  ILdialog.visible = false
}
</script>

<template>
<instruct-log :visible="ILdialog.visible" @closeILdialog="closeILdialog"></instruct-log>
</template>

四、监听组件属性变动

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

// 监听visible
watch(() => props.visible, (newV) => {
  if(newV) {
    // ...
  }
})

五、自定义指令

部分指令:

<script setup lang="ts">
const vFoo = {
  mounted(el: any, binding: any) {
    console.log(binding.value) // 123
  }
}
</script>

<template>
<div v-foo="123" v-auth="true"></div>
</template>

[warning] 留神:部分指令定义须要 v 结尾,如:vFoo,这样能力辨认到 v-foo 指令

全局指令:

const app = createApp(App)

// 权限指令
app.directive('auth', {
  mounted(el: any, binding: any) {
    if(!binding.value) {
      el.parentNode.removeChild(el)
    }
  }
})

更多前端常识,请关注小程序,不定期有惊喜!

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理