Vue3從入門到精通(二)

来源:https://www.cnblogs.com/for-easy-fast/archive/2023/06/08/17465813.html
-Advertisement-
Play Games

vue3 偵聽器 在Vue3中,偵聽器的使用方式與Vue2相同,可以使用watch選項或$watch方法來創建偵聽器。不同之處在於,Vue3中取消了immediate選項,同時提供了新的選項和API。 創建偵聽器 可以使用watch選項或$watch方法來創建偵聽器,語法與Vue2相同。示例如下: ...


vue3 偵聽器

在Vue3中,偵聽器的使用方式與Vue2相同,可以使用watch選項或$watch方法來創建偵聽器。不同之處在於,Vue3中取消了immediate選項,同時提供了新的選項和API。

  1. 創建偵聽器

可以使用watch選項或$watch方法來創建偵聽器,語法與Vue2相同。示例如下:

<template>
  <div>{{ message }}</div>
</template>
​
<script>
export default {
  data() {
    return {
      message: 'Hello, Vue3!'
    }
  },
  watch: {
    message(newValue, oldValue) {
      console.log(`New value: ${newValue}, old value: ${oldValue}`)
    }
  }
}
</script>

上面的代碼中,使用watch選項來創建偵聽器,當message的值發生變化時,會觸發偵聽器函數。

  1. 偵聽多個屬性

在Vue3中,可以使用數組的方式偵聽多個屬性。示例如下:

<template>
  <div>{{ fullName }}</div>
</template>
​
<script>
export default {
  data() {
    return {
      firstName: 'John',
      lastName: 'Doe'
    }
  },
  watch: {
    ['firstName', 'lastName'](newValues, oldValues) {
      console.log(`New values: ${newValues}, old values: ${oldValues}`)
    }
  },
  computed: {
    fullName() {
      return `${this.firstName} ${this.lastName}`
    }
  }
}
</script>

上面的代碼中,使用數組的方式偵聽firstNamelastName兩個屬性,當它們的值發生變化時,會觸發偵聽器函數。

  1. 深度偵聽

在Vue3中,可以使用deep選項來實現深度偵聽。示例如下:

<template>
  <div>{{ user.name }}</div>
</template>
​
<script>
export default {
  data() {
    return {
      user: {
        name: 'John Doe',
        age: 30
      }
    }
  },
  watch: {
    user: {
      handler(newValue, oldValue) {
        console.log(`New value: ${JSON.stringify(newValue)}, old value: ${JSON.stringify(oldValue)}`)
      },
      deep: true
    }
  }
}
</script>

上面的代碼中,使用deep選項來實現深度偵聽user對象的所有屬性,當user對象的任何屬性發生變化時,都會觸發偵聽器函數。

  1. 取消偵聽器

在Vue3中,可以使用watch選項返回的取消函數來取消偵聽器。示例如下:

<template>
  <div>{{ message }}</div>
</template>
​
<script>
export default {
  data() {
    return {
      message: 'Hello, Vue3!'
    }
  },
  mounted() {
    const unwatch = this.$watch('message', (newValue, oldValue) => {
      console.log(`New value: ${newValue}, old value: ${oldValue}`)
    })
​
    setTimeout(() => {
      unwatch()
    }, 5000)
  }
}
</script>

上面的代碼中,使用$watch方法創建偵聽器,並將返回的取消函數存儲在unwatch變數中,在5秒後調用取消函數,取消偵聽器。

vue3 表單輸入綁定

在Vue3中,表單輸入綁定的方式與Vue2相同,可以使用v-model指令來實現。不同之處在於,Vue3中取消了.sync修飾符,同時提供了新的修飾符和API。

  1. 基本用法

使用v-model指令可以將表單元素的值與組件的數據進行雙向綁定。示例如下:

<template>
  <div>
    <input type="text" v-model="message">
    <p>{{ message }}</p>
  </div>
</template>
​
<script>
export default {
  data() {
    return {
      message: ''
    }
  }
}
</script>

上面的代碼中,將input元素的值與message數據進行雙向綁定,當input元素的值發生變化時,message數據也會跟著變化,同時p元素中展示message數據的值。

  1. 修飾符

在Vue3中,提供了新的修飾符來實現更靈活的表單輸入綁定。

  • .lazy修飾符:在輸入框失去焦點或按下回車鍵後才更新數據。示例如下:

<template>
  <div>
    <input type="text" v-model.lazy="message">
    <p>{{ message }}</p>
  </div>
</template>
​
<script>
export default {
  data() {
    return {
      message: ''
    }
  }
}
</script>

上面的代碼中,使用.lazy修飾符將輸入框的值在失去焦點或按下回車鍵後才更新message數據。

  • .trim修飾符:去除輸入框的首尾空格。示例如下:

<template>
  <div>
    <input type="text" v-model.trim="message">
    <p>{{ message }}</p>
  </div>
</template>
​
<script>
export default {
  data() {
    return {
      message: ''
    }
  }
}
</script>

上面的代碼中,使用.trim修飾符去除輸入框的首尾空格,並將處理後的值綁定到message數據上。

  • .number修飾符:將輸入框的值轉換為數字類型。示例如下:

<template>
  <div>
    <input type="text" v-model.number="age">
    <p>{{ age }}</p>
  </div>
</template>
​
<script>
export default {
  data() {
    return {
      age: 0
    }
  }
}
</script>

上面的代碼中,使用.number修飾符將輸入框的值轉換為數字類型,並將轉換後的值綁定到age數據上。

  1. 自定義組件

在自定義組件中,可以使用v-model指令來實現自定義組件的雙向綁定。示例如下:

<template>
  <div>
    <my-input v-model="message"></my-input>
    <p>{{ message }}</p>
  </div>
</template>
​
<script>
import MyInput from './MyInput.vue'
​
export default {
  components: {
    MyInput
  },
  data() {
    return {
      message: ''
    }
  }
}
</script>

上面的代碼中,使用v-model指令將my-input組件的值與message數據進行雙向綁定,當my-input組件的值發生變化時,message數據也會跟著變化,同時p元素中展示message數據的值。需要註意的是,my-input組件內部需要使用$emit方法觸發input事件來實現數據的更新。

vue3 模板引用

在Vue3中,模板引用使用ref來實現。ref可以用來獲取組件實例或DOM元素的引用,並將其綁定到組件實例的數據上。

  1. 組件引用

在Vue3中,使用ref可以獲取到組件實例的引用。示例如下:

<template>
  <div>
    <my-component ref="myComponent"></my-component>
  </div>
</template>
​
<script>
import MyComponent from './MyComponent.vue'
​
export default {
  components: {
    MyComponent
  },
  mounted() {
    console.log(this.$refs.myComponent) // 輸出組件實例
  }
}
</script>

上面的代碼中,使用ref獲取到my-component組件的實例,並將其綁定到myComponent數據上。在mounted鉤子函數中,可以通過this.$refs.myComponent獲取到組件實例,併進行操作。

  1. DOM元素引用

在Vue3中,使用ref可以獲取到DOM元素的引用。示例如下:

<template>
  <div>
    <input type="text" ref="myInput">
  </div>
</template>
​
<script>
export default {
  mounted() {
    console.log(this.$refs.myInput) // 輸出DOM元素
  }
}
</script>

上面的代碼中,使用ref獲取到input元素的引用,並將其綁定到myInput數據上。在mounted鉤子函數中,可以通過this.$refs.myInput獲取到DOM元素,併進行操作。

需要註意的是,在Vue3中,ref只能綁定到組件實例或DOM元素上,不能綁定到普通數據上。

vue3 組件組成

在Vue3中,組件由三部分組成:模板、邏輯和樣式。其中,模板和邏輯與Vue2中的組件相同,而樣式方面,Vue3推薦使用CSS Modules和CSS Variables來實現。

  1. 模板

組件的模板與Vue2中的模板相同,使用template標簽來定義。示例如下:

<template>
  <div>
    <h1>{{ title }}</h1>
    <p>{{ content }}</p>
  </div>
</template>
​
<script>
export default {
  data() {
    return {
      title: 'Hello, Vue3!',
      content: 'Vue3 is awesome!'
    }
  }
}
</script>

上面的代碼中,定義了一個簡單的組件模板,包含一個標題和一段文本內容,使用雙花括弧綁定數據。

  1. 邏輯

組件的邏輯與Vue2中的邏輯相同,使用script標簽來定義。示例如下:

<template>
  <div>
    <h1>{{ title }}</h1>
    <p>{{ content }}</p>
  </div>
</template>
​
<script>
export default {
  data() {
    return {
      title: 'Hello, Vue3!',
      content: 'Vue3 is awesome!'
    }
  },
  methods: {
    handleClick() {
      console.log('clicked')
    }
  }
}
</script>

上面的代碼中,定義了一個簡單的組件邏輯,包含一個data數據對象和一個handleClick方法。

  1. 樣式

在Vue3中,推薦使用CSS Modules和CSS Variables來實現組件樣式。CSS Modules可以避免全局樣式的污染,而CSS Variables可以實現更靈活的樣式控制。

使用CSS Modules時,可以在style標簽中設置module屬性來啟用CSS Modules。示例如下:

<template>
  <div class="wrapper">
    <h1 class="title">{{ title }}</h1>
    <p class="content">{{ content }}</p>
  </div>
</template>
​
<script>
export default {
  data() {
    return {
      title: 'Hello, Vue3!',
      content: 'Vue3 is awesome!'
    }
  }
}
</script>
​
<style module>
.wrapper {
  padding: 20px;
  background-color: #f5f5f5;
}
​
.title {
  font-size: 24px;
  color: var(--primary-color);
}
​
.content {
  font-size: 16px;
  color: #333;
}
</style>

上面的代碼中,使用CSS Modules設置了.wrapper.title.content三個類的樣式,並使用CSS Variables設置了--primary-color變數的值。

需要註意的是,使用CSS Modules時,類名會被自動轉換為唯一的類名,可以通過$style來引用。示例如下:

<template>
  <div :class="$style.wrapper">
    <h1 :class="$style.title">{{ title }}</h1>
    <p :class="$style.content">{{ content }}</p>
  </div>
</template>
​
<script>
export default {
  data() {
    return {
      title: 'Hello, Vue3!',
      content: 'Vue3 is awesome!'
    }
  }
}
</script>
​
<style module>
.wrapper {
  padding: 20px;
  background-color: #f5f5f5;
}
​
.title {
  font-size: 24px;
  color: var(--primary-color);
}
​
.content {
  font-size: 16px;
  color: #333;
}
</style>

上面的代碼中,使用$style引用了.wrapper.title.content三個類的樣式。

vue3 組件嵌套關係

在Vue3中,組件嵌套關係與Vue2中的組件嵌套關係相同,通過在模板中嵌套組件來實現。

例如,有兩個組件ParentChild,其中Parent組件中嵌套了Child組件。示例如下:

<template>
  <div>
    <h1>{{ title }}</h1>
    <child :content="content"></child>
  </div>
</template>
​
<script>
import Child from './Child.vue'
​
export default {
  components: {
    Child
  },
  data() {
    return {
      title: 'Parent Component',
      content: 'This is the content of Parent Component.'
    }
  }
}
</script>

上面的代碼中,Parent組件中通過<child>標簽嵌套了Child組件,並將content數據傳遞給Child組件。

Child組件的代碼如下:

<template>
  <div>
    <h2>{{ title }}</h2>
    <p>{{ content }}</p>
  </div>
</template>
​
<script>
export default {
  props: {
    content: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      title: 'Child Component'
    }
  }
}
</script>

上面的代碼中,Child組件接收了Parent組件傳遞的content數據,併在模板中展示出來。

需要註意的是,當組件嵌套層級較深時,可以使用provideinject來實現跨層級傳遞數據,避免層層傳遞數據的麻煩。

vue3 組件註冊方式

在Vue3中,組件註冊方式與Vue2中的組件註冊方式有所不同,Vue3提供了defineComponent函數來定義組件。具體步驟如下:

  1. 創建組件

使用defineComponent函數創建組件,示例如下:

import { defineComponent } from 'vue'
​
export default defineComponent({
  name: 'MyComponent',
  props: {
    content: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    return {
      title: 'My Component',
      handleClick() {
        console.log('clicked')
      }
    }
  },
  template: `
    <div>
      <h1>{{ title }}</h1>
      <p>{{ content }}</p>
      <button @click="handleClick">Click Me</button>
    </div>
  `
})

上面的代碼中,使用defineComponent函數定義了一個名為MyComponent的組件,包含propssetuptemplate三個部分。其中,props定義了組件的屬性,setup定義了組件的邏輯,template定義了組件的模板。

  1. 註冊組件

使用createApp函數創建Vue實例,並使用component方法註冊組件,示例如下:

import { createApp } from 'vue'
import MyComponent from './MyComponent.vue'
​
const app = createApp()
​
app.component('my-component', MyComponent)
​
app.mount('#app')

上面的代碼中,使用component方法將MyComponent組件註冊為my-component組件,並使用mount方法將Vue實例掛載到DOM節點上。

需要註意的是,使用defineComponent函數創建的組件可以直接在component方法中註冊,無需再進行額外的處理。另外,也可以使用defineAsyncComponent函數定義非同步組件,以優化應用的載入性能。

vue3 組件傳遞數據 props

在Vue3中,組件傳遞數據的方式與Vue2中基本相同,都是通過props屬性進行傳遞。但是Vue3中對props進行了一些優化,使得組件傳遞數據更加方便和靈活。

下麵是一個簡單的示例,演示瞭如何在Vue3中使用props傳遞數據:

// ChildComponent.vue
<template>
  <div>
    <h2>{{ title }}</h2>
    <p>{{ content }}</p>
  </div>
</template>
​
<script>
  import { defineComponent } from 'vue'
​
  export default defineComponent({
    name: 'ChildComponent',
    props: {
      title: {
        type: String,
        required: true
      },
      content: {
        type: String,
        default: ''
      }
    }
  })
</script>
// ParentComponent.vue
<template>
  <div>
    <h1>{{ pageTitle }}</h1>
    <child-component :title="childTitle" :content="childContent" />
  </div>
</template>
​
<script>
  import { defineComponent } from 'vue'
  import ChildComponent from './ChildComponent.vue'
​
  export default defineComponent({
    name: 'ParentComponent',
    components: {
      ChildComponent
    },
    data() {
      return {
        pageTitle: 'Parent Component',
        childTitle: 'Child Component',
        childContent: 'Lorem ipsum dolor sit amet'
      }
    }
  })
</script>

在上面的示例中,ChildComponent組件定義了兩個propstitlecontenttitle屬性是必需的,類型為字元串;content屬性是可選的,類型為字元串,如果沒有傳遞則預設為空字元串。

ParentComponent組件中,使用child-component標簽引入了ChildComponent組件,並通過:title:content指令將數據傳遞給子組件。在data中定義了pageTitlechildTitlechildContent三個屬性,分別用於在父組件和子組件中顯示標題和內容。

需要註意的是,在Vue3中,使用props傳遞數據時,可以通過.sync修飾符實現雙向綁定,也可以使用v-model指令簡化雙向綁定的寫法。此外,還可以使用emit方法向父組件發送事件,實現組件之間的通信。

vue3 組件傳遞多種數據類型

在Vue3中,組件傳遞多種數據類型的方式與Vue2中基本相同,都是通過props屬性進行傳遞。下麵是一個示例,演示瞭如何在Vue3中使用props傳遞多種數據類型:

// ChildComponent.vue
<template>
  <div>
    <h2>{{ title }}</h2>
    <p>{{ content }}</p>
    <ul>
      <li v-for="item in list" :key="item.id">{{ item.name }}</li>
    </ul>
  </div>
</template>
​
<script>
  import { defineComponent } from 'vue'
​
  export default defineComponent({
    name: 'ChildComponent',
    props: {
      title: {
        type: String,
        required: true
      },
      content: {
        type: String,
        default: ''
      },
      list: {
        type: Array,
        default: () => []
      }
    }
  })
</script>

在上面的示例中,ChildComponent組件定義了三個propstitlecontentlisttitle屬性是必需的,類型為字元串;content屬性是可選的,類型為字元串,如果沒有傳遞則預設為空字元串;list屬性是可選的,類型為數組,如果沒有傳遞則預設為空數組。

在父組件中,可以通過:title:content:list指令將數據傳遞給子組件。需要註意的是,如果要傳遞數組類型的數據,可以使用v-bind指令或簡寫的:語法,例如:list="[ { id: 1, name: 'item 1' }, { id: 2, name: 'item 2' } ]"

需要註意的是,在Vue3中,使用props傳遞數據時,可以通過.sync修飾符實現雙向綁定,也可以使用v-model指令簡化雙向綁定的寫法。此外,還可以使用emit方法向父組件發送事件,實現組件之間的通信。

vue3 組件傳遞props 校驗

在Vue3中,組件傳遞props時,可以使用Props選項進行校驗。Props選項是一個對象,用於指定組件接受的props以及其類型、預設值和校驗規則等。

下麵是一個示例,演示瞭如何在Vue3中使用Props選項進行校驗:

// ChildComponent.vue
<template>
  <div>
    <h2>{{ title }}</h2>
    <p>{{ content }}</p>
    <ul>
      <li v-for="item in list" :key="item.id">{{ item.name }}</li>
    </ul>
  </div>
</template>
​
<script>
  import { defineComponent } from 'vue'
​
  export default defineComponent({
    name: 'ChildComponent',
    props: {
      // 校驗title屬性,類型為字元串,必須傳遞
      title: {
        type: String,
        required: true
      },
      // 校驗content屬性,類型為字元串,如果沒有傳遞則預設為空字元串
      content: {
        type: String,
        default: ''
      },
      // 校驗list屬性,類型為數組,如果沒有傳遞則預設為空數組
      list: {
        type: Array,
        default: () => []
      },
      // 校驗count屬性,類型為數字,必須大於0
      count: {
        type: Number,
        validator: (value) => value > 0
      }
    }
  })
</script>

在上面的示例中,ChildComponent組件定義了四個propstitlecontentlistcount。其中,titlecount屬性是必需的,類型分別為字元串和數字;contentlist屬性是可選的,類型分別為字元串和數組,如果沒有傳遞則分別預設為空字元串和空數組。此外,count屬性還定義了一個校驗規則,即必須大於0。

需要註意的是,在Vue3中,如果一個props屬性沒有指定類型,那麼它可以接受任何類型的數據。如果需要限制props屬性接受的數據類型,可以使用type選項指定。如果需要指定多個類型,可以使用數組形式,例如type: [String, Number]

此外,如果需要對props屬性進行更複雜的校驗,可以使用validator選項。validator是一個函數,用於校驗props屬性的值是否符合指定的規則。如果校驗失敗,可以返回false或拋出異常,Vue會在控制台輸出警告信息。

vue3 組件事件

在Vue3中,組件事件可以使用emits選項進行定義。emits選項是一個數組,用於指定組件可以觸發的事件名稱。定義組件事件後,可以使用$emit方法在組件內部觸發事件,並可以在父組件中使用v-on指令監聽事件。

下麵是一個示例,演示瞭如何在Vue3中定義組件事件:

// ChildComponent.vue
<template>
  <button @click="handleClick">{{ buttonText }}</button>
</template>

<script>
  import { defineComponent } from 'vue'

  export default defineComponent({
    name: 'ChildComponent',
    emits: ['click'],
    props: {
      buttonText: {
        type: String,
        required: true
      }
    },
    methods: {
      handleClick() {
        this.$emit('click')
      }
    }
  })
</script>

在上面的示例中,ChildComponent組件定義了一個emits選項,指定了可以觸發的click事件。在組件內部,使用$emit方法觸發click事件,併在父組件中使用v-on指令監聽該事件。

下麵是父組件如何監聽ChildComponent組件觸發的click事件:

// ParentComponent.vue
<template>
  <div>
    <ChildComponent :buttonText="buttonText" @click="handleClick" />
  </div>
</template>
​
<script>
  import { defineComponent } from 'vue'
  import ChildComponent from './ChildComponent.vue'
​
  export default defineComponent({
    name: 'ParentComponent',
    components: {
      ChildComponent
    },
    data() {
      return {
        buttonText: 'Click me'
      }
    },
    methods: {
      handleClick() {
        console.log('ChildComponent clicked')
      }
    }
  })
</script>

在上面的示例中,ParentComponent組件使用v-on指令監聽ChildComponent組件觸發的click事件,併在handleClick方法中輸出一條日誌。

需要註意的是,在Vue3中,如果一個組件觸發了未定義的事件,Vue會在控制台輸出警告信息。如果需要禁用這個警告,可以在createApp方法中傳遞一個config選項,設置warnHandler屬性為null。例如:

import { createApp } from 'vue'
​
const app = createApp({
  // ...
})
​
app.config.warnHandler = null
​
app.mount('#app')

vue3 組件事件配合v-model使用

在Vue3中,組件事件可以配合v-model指令使用,用於實現雙向數據綁定。要實現v-model指令,需要在組件中定義一個名為modelValue的prop,併在emits選項中指定update:modelValue事件。

以下是一個示例,演示瞭如何在Vue3中使用v-model指令:

// ChildComponent.vue
<template>
  <input :value="modelValue" @input="handleInput" />
</template>
​
<script>
  import { defineComponent } from 'vue'
​
  export default defineComponent({
    name: 'ChildComponent',
    emits: ['update:modelValue'],
    props: {
      modelValue: {
        type: String,
        required: true
      }
    },
    methods: {
      handleInput(event) {
        this.$emit('update:modelValue', event.target.value)
      }
    }
  })
</script>

在上面的示例中,ChildComponent組件定義了一個名為modelValue的prop,併在emits選項中指定了update:modelValue事件。在組件內部,使用$emit方法觸發update:modelValue事件,並傳遞輸入框的值。

下麵是父組件如何使用v-model指令綁定ChildComponent組件的modelValue

// ParentComponent.vue
<template>
  <div>
    <ChildComponent v-model="inputValue" />
  </div>
</template>
​
<script>
  import { defineComponent, ref } from 'vue'
  import ChildComponent from './ChildComponent.vue'
​
  export default defineComponent({
    name: 'ParentComponent',
    components: {
      ChildComponent
    },
    setup() {
      const inputValue = ref('')
​
      return {
        inputValue
      }
    }
  })
</script>

在上面的示例中,ParentComponent組件使用v-model指令綁定ChildComponent組件的modelValue,並將其賦值給inputValue變數。此時,ChildComponent組件的輸入框和inputValue變數會實現雙向數據綁定。

需要註意的是,v-model指令實際上是語法糖,相當於同時綁定了一個value prop和一個update:value事件。因此,如果需要在組件內部使用v-model指令,也需要定義一個名為value的prop,併在emits選項中指定update:value事件。

vue3 組件數據傳遞

在 Vue3 中,組件數據傳遞可以通過 props 和 emit 實現。

  1. Props

在 Vue3 中,通過 props 定義組件的屬性,可以將數據從父組件傳遞到子組件。父組件中使用子組件時,可以通過 v-bind 或簡寫的 : 來綁定屬性值。

例如,下麵的代碼演示瞭如何使用 props 在父組件中向子組件傳遞數據:

// ChildComponent.vue
<template>
  <div>{{ message }}</div>
</template>

<script>
  import { defineComponent, PropType } from 'vue'

  export default defineComponent({
    name: 'ChildComponent',
    props: {
      message: {
        type: String,
        required: true
      }
    }
  })
</script>

// ParentComponent.vue
<template>
  <div>
    <ChildComponent :message="parentMessage" />
  </div>
</template>

<script>
  import { defineComponent } from 'vue'
  import ChildComponent from './ChildComponent.vue'

  export default defineComponent({
    name: 'ParentComponent',
    components: {
      ChildComponent
    },
    data() {
      return {
        parentMessage: 'Hello from parent component'
      }
    }
  })
</script>

在上面的代碼中,ChildComponent 組件定義了一個名為 messageprops,併在模板中使用它來顯示數據。在 ParentComponent 組件中,使用 v-bind 或簡寫的 : 來將父組件的 parentMessage 數據傳遞給子組件的 message 屬性。

  1. Emit

在 Vue3 中,通過 emit 發送自定義事件,可以將數據從子組件傳遞到父組件。子組件使用 $emit 方法觸發事件,並傳遞數據。父組件中通過 v-on 或簡寫的 @ 來監聽事件,併在事件處理函數中獲取數據。

例如,下麵的代碼演示瞭如何使用 emit 在子組件中向父組件傳遞數據:

// ChildComponent.vue
<template>
  <button @click="sendMessage">Send message to parent</button>
</template>
​
<script>
  import { defineComponent } from 'vue'
​
  export default defineComponent({
    name: 'ChildComponent',
    methods: {
      sendMessage() {
        this.$emit('message-sent', 'Hello from child component')
      }
    }
  })
</script>
​
// ParentComponent.vue
<template>
  <div>
    <ChildComponent @message-sent="handleMessage" />
    <div>{{ message }}</div>
  </div>
</template>
​
<script>
  import { defineComponent, ref } from 'vue'
  import ChildComponent from './ChildComponent.vue'
​
  export default defineComponent({
    name: 'ParentComponent',
    components: {
      ChildComponent
    },
    setup() {
      const message = ref('')
​
      const handleMessage = (data) => {
        message.value = data
      }
​
      return {
        message,
        handleMessage
      }
    }
  })
</script>

在上面的代碼中,ChildComponent 組件定義了一個 sendMessage 方法,在方法中使用 $emit 方法觸發 message-sent 事件,並將數據傳遞給父組件。在 ParentComponent 組件中,使用 v-on 或簡寫的 @ 來監聽 message-sent 事件,併在事件處理函數中獲取數據。

vue3 透傳Attributes

在 Vue3 中,可以使用 v-bind="$attrs" 透傳父組件的 attributes 到子組件,子組件可以通過 inheritAttrs: false 禁用繼承父組件的 attributes,然後使用 $attrs 獲取透傳的 attributes。

例如,下麵的代碼演示瞭如何使用 $attrs 透傳父組件的 attributes 到子組件:

// ChildComponent.vue
<template>
  <div :class="computedClass" v-bind="$attrs">{{ message }}</div>
</template>
​
<script>
  import { defineComponent } from 'vue'
​
  export default defineComponent({
    name: 'ChildComponent',
   

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • ## 配置AOSP docker編譯環境 ### 1.安裝docker ``` curl -fsSL https://get.docker.com -o get-docker.sh sh get-docker.sh ``` 參考:[github](https://github.com/docker/ ...
  • # 協程中的異常處理 ![coroutine exception handling](https://img2023.cnblogs.com/blog/325852/202306/325852-20230608084235670-684439238.png) ## Parent-Child關係 如果 ...
  • 基於electron25+vite4+vue3仿製chatgpt客戶端聊天模板ElectronChatGPT。 electron-chatgpt 使用最新桌面端技術Electron25.x結合Vite4.x全家桶技術開發跨端模仿ChatGPT智能聊天程式模板。支持經典+分欄兩種佈局、暗黑+明亮主題模 ...
  • 近期發現公司某些站點出現偶爾跳轉博彩網站的現象,經過排查發現該現象為供應鏈投毒攻擊,BootCDN上的靜態資源無一例外均被污染, 當外站引入BootCDN的靜態資源時,如果請求攜帶的Referer頭為指定值(涉及公司隱私不便透露),User-Agent頭為手機瀏覽器UA,觸發惡意代碼註入。 例如:h ...
  • Collapse 摺疊面板:通過摺疊面板收納內容區域。 1. 基礎用法 可以摺疊展開多個面板,面板之間互不影響。 示例代碼 <el-collapse v-model="activeNames" @change="handleChange"> <el-collapse-item title="一致性 ...
  • 這裡給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 為了保證的可讀性,本文采用意譯而非直譯。 在 JS 面試中,經常會看到一些簡單而又沙雕的題目,這些題目包含一些陷阱,但這些在我們規範的編碼下或者業務中基本不會出現。 有些面試官就是這樣,不專註於制定代碼的標準和規範上,卻用不規範的代碼去檢 ...
  • # 解決JavaScript單線程問題——webWorkers > 參考文檔 [使用 Web Workers - Web API 介面參考 | MDN (mozilla.org)](https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Worker ...
  • 基礎知識 知識點梳理見圖: 自己動手實踐案例 案例1: 訪問本地文件 <!DOCTYPE html> <html> <body> <div id="demo"> <h1>XMLHttpRequest 對象</h1> <button type="button" onclick="loadDoc()"> ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...