全篇主要介绍vue3的写法
1.父子组件数据传递
父传子 props 需要使用 defineProps()
这个宏函数来进行声明
<!-- 父组件 -->
<script setup>
import ChildView from './ChildView.vue'
</script>
<template>
<ChildView some-prop="parent message" />
</template>
<!-- 子组件 -->
<script setup>
const props = defineProps({
someProp: {
type: String,
required: true
}
})
console.log(props.someProp) // parent message
</script>
<template>
<!-- 使用 someProp 或 props.someProp -->
<div>{{ someProp }}</div>
<div>{{ props.someProp }}</div>
</template>
子传父 需要使用 defineEmits()
<!-- 子组件 -->
<script setup>
const emit = defineEmits(['someEvent'])
function onClick() {
emit('someEvent', 'child message')
}
</script>
<template>
<button @click="onClick">点击</button>
</template>
<!-- 父组件 -->
<script setup>
import ChildView from './ChildView.vue'
function someEvent(value) {
console.log(value) // child message
}
</script>
<template>
<ChildView @some-event="someEvent" />
</template>
父组件使用子组件数据 子组件通过 defineExpose
显式的暴露出去
<!-- 子组件 -->
<script setup>
import { ref } from 'vue'
const msg = ref('hello vue3!')
function change() {
msg.value = 'hi vue3!'
console.log(msg.value)
}
// 属性或方法必须暴露出去,父组件才能使用
defineExpose({ msg, change })
</script>
<!-- 父组件 -->
<script setup>
import ChildView from './ChildView.vue'
import { ref, onMounted } from 'vue'
const child = ref(null)
onMounted(() => {
console.log(child.value.msg) // hello vue3!
child.value.change() // hi vue3!
})
</script>
<template>
<ChildView ref="child"></ChildView>
</template>
2.路由跳转,获取路由参数
使用 vue-router
提供的 useRouter
方法,来进行路由跳转:
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
function onClick() {
router.push({
path: '/about',
query: {
msg: 'hello vue3!'
}
})
}
</script>
当我们要获取路由参数时,可以使用 vue-router
提供的 useRoute
方法:
<script setup>
import { useRoute } from 'vue-router'
const route = useRoute()
console.log(route.query.msg) // hello vue3!
</script>
3.插槽的使用
通过 v-slot
这个指令来指定模板的位置,同时获取作用域插槽的数据
<!-- 父组件 -->
<script setup>
import ChildView from './ChildView.vue'
</script>
<template>
<div>parent</div>
<ChildView>
<template v-slot:content="{ msg }">
<div>{{ msg }}</div>
</template>
</ChildView>
</template>
<!-- ChildView 也可以简写为: -->
<ChildView>
<template #content="{ msg }">
<div>{{ msg }}</div>
</template>
</ChildView>
<!-- 子组件 -->
<template>
<div>child</div>
<slot name="content" msg="hello vue3!"></slot>
</template>
4.缓存路由组件
使用 KeepAlive
包裹 Component
。但缓存路由组件,Vue3 需要结合插槽一起使用:
// Vue3 中缓存路由组件
<RouterView v-slot="{ Component }">
<KeepAlive>
<Component :is="Component"></Component>
</KeepAlive>
</RouterView>
5.生命周期
Vue3
生命周期钩子都以 on
开头,并且需要在组件中手动导入。
<script setup>
import { onMounted } from 'vue'
onMounted(() => {
console.log('onMounted')
})
</script>