当前位置:实例文章 » HTML/CSS实例» [文章]初识vue3/setup/ ref()/ computed/watch/生命周期/父传子

初识vue3/setup/ ref()/ computed/watch/生命周期/父传子

发布人:shili8 发布时间:2025-02-03 07:38 阅读次数:0

**Vue3 的基本概念**

Vue3 是一个新版本的 Vue 框架,相比于之前的 Vue2.x 版本,它带来了许多新的特性和改进。下面我们将逐一介绍这些基本概念。

###1. setup()

`setup()` 是 Vue3 中的一个新函数,它用于定义组件的初始状态和计算属性。在 Vue2.x 中,我们使用 `data()` 和 `computed()` 来实现类似的功能,但是在 Vue3 中,`setup()` 函数取代了它们。

javascript// Vue2.xexport default {
 data() {
 return { count:0 }
 },
 computed: {
 doubleCount() {
 return this.count *2 }
 }
}

// Vue3import { ref } from 'vue'

export default {
 setup() {
 const count = ref(0)
 const doubleCount = computed(() => count.value *2)

 // ...
 }
}


###2. ref()

`ref()` 是一个函数,它用于创建一个响应式的值。在 Vue3 中,我们使用 `ref()` 来定义组件的初始状态。

javascriptimport { ref } from 'vue'

export default {
 setup() {
 const count = ref(0)

 // ...
 }
}


###3. computed()

`computed()` 是一个函数,它用于创建一个计算属性。在 Vue3 中,我们使用 `computed()` 来定义组件的计算属性。

javascriptimport { computed } from 'vue'

export default {
 setup() {
 const count = ref(0)
 const doubleCount = computed(() => count.value *2)

 // ...
 }
}


###4. watch()

`watch()` 是一个函数,它用于监听组件的属性变化。在 Vue3 中,我们使用 `watch()` 来定义组件的侦听器。

javascriptimport { watch } from 'vue'

export default {
 setup() {
 const count = ref(0)
 watch(() => count.value, (newCount) => {
 console.log(`count changed to ${newCount}`)
 })

 // ...
 }
}


###5. 生命周期生命周期是 Vue 组件的执行顺序。在 Vue3 中,我们使用 `onMounted()`, `onUpdated()`, 和 `onUnmounted()` 来定义组件的生命周期函数。

javascriptimport { onMounted, onUpdated, onUnmounted } from 'vue'

export default {
 setup() {
 const count = ref(0)

 onMounted(() => {
 console.log('mounted')
 })

 onUpdated(() => {
 console.log('updated')
 })

 onUnmounted(() => {
 console.log('unmounted')
 })

 // ...
 }
}


###6. 父传子父组件可以通过 `$emit()` 来向子组件发送事件。在 Vue3 中,我们使用 `useEmit()` 来定义组件的事件侦听器。

javascriptimport { useEmit } from 'vue'

export default {
 setup() {
 const count = ref(0)

 useEmit('countChanged', () => {
 console.log(`count changed to ${count.value}`)
 })

 // ...
 }
}


子组件可以通过 `$on()` 来侦听父组件发送的事件。

javascriptimport { onMounted, onUpdated } from 'vue'

export default {
 setup() {
 const count = ref(0)

 onMounted(() => {
 console.log('mounted')
 })

 onUpdated(() => {
 console.log('updated')
 })

 // ...
 }
}


### 总结Vue3 是一个新版本的 Vue 框架,它带来了许多新的特性和改进。通过使用 `setup()`, `ref()`, `computed()`, `watch()`, 生命周期函数,和事件侦听器,我们可以更好地理解和使用 Vue3 的基本概念。

### 参考* [Vue3 文档]( />* [Vue3 API 文档](

其他信息

其他资源

Top