Vue3 组件及其生命周期

Vue3 组件及其生命周期

每一个 .vue 都可以充当组件来使用 每一个组件都可以复用

组件使用示例

<script setup lang="ts">
import HelloWorld from ./components/HelloWorld.vue
// vue3 setup 语法糖组件无需声明式注册
// components: {
            
     
//   HelloWorld
// }
</script>

<template>
  <div>
    <HelloWorld msg="Hello,Vue3"/>
  </div>
</template>

组件的生命周期

vue2 组件的生命周期

Vue3 钩子函数

beforeCreate -> 使用 setup()
    created -> 使用 setup()
    beforeMount -> onBeforeMount
    mounted -> onMounted
    beforeUpdate -> onBeforeUpdate
    updated -> onUpdated
    beforeDestroy -> onBeforeUnmount
    destroyed -> onUnmounted
    errorCaptured -> onErrorCaptured
<script setup lang="ts">
import HelloWorld from ./components/HelloWorld.vue
import {
            
     ref} from "vue";
let flag = ref<boolean>(true)
const unmountHelloWorld = () => {
            
     
  flag.value = !flag.value
}
</script>

<template>
  <div>
    <HelloWorld msg="Hello,Vue3" v-if="flag"/>
  </div>
  <div>
    <button @click="unmountHelloWorld">改变组件状态</button>
  </div>
</template>
<script setup lang="ts">
import {
            
      ref } from vue
import {
            
     onBeforeMount, onBeforeUnmount, onBeforeUpdate, 
		onMounted, onUnmounted, onUpdated} from "vue";

defineProps<{
            
      msg: string }>()

let count = ref(0)
console.log("setup-----")
// 组件挂载之前(dom没有渲染完成,无法获取)
onBeforeMount(() => {
            
     
  console.log("组件挂载之前执行 ===> onBeforeMount")
  let hello = document.querySelector("#hello")
  console.log("无法获取dom ===> ",hello)
})
onMounted(() => {
            
     
  console.log("组件挂载完毕 ===> onMounted")
  let hello = document.querySelector("#hello")
  console.log("可以获取dom ===> ",hello)
})
// 依赖于组件内响应式数据的变化
onBeforeUpdate(() => {
            
     
  console.log("组件更新之前 ===> onBeforeUpdate")
  console.log(count.value)
})
onUpdated(() => {
            
     
  console.log("组件更新完毕 ===> onUpdated")
  console.log(count.value)
})
onBeforeUnmount(() => {
            
     
  console.log("组件卸载之前 ===> onBeforeUnmount")
})
onUnmounted(() => {
            
     
  console.log("组件卸载完毕 ===> onUnmount")
})
</script>

<template>
  <h1>{
         
  { msg }}</h1>
  <div id="hello">
    <div>
      <button @click="count--">-</button>
      <span>{
         
  { count }}</span>
      <button @click="count++">+</button>
    </div>
  </div>
</template>

组件实操以及认识 less和scoped

认识 Less

什么是less

Less (Leaner Style Sheets) 是一门向后兼容的 CSS 扩展语言

在 vite 中使用 less

1.安装

npm install less-loader -D

2.使用(在style标签内注明 lang=“less” 即可)

<style lang="less">

</style>

认识 scoped

什么是 scoped

实现组件的私有化,当前 style 属性 只属于当前模块

经验分享 程序员 微信小程序 职场和发展