setup() 函数setup() 是Vue 3引入的一个新的组件选项,用于定义组件的逻辑。它在组件初始化阶段被调用,替代了Vue 2中的data、methods等选项。props和context作为参数。import { ref } from 'vue'
export default {
setup(props, context) {
const count = ref(0)
const increment = () => {
count.value++
}
return { count, increment }
}
}
ref() 函数const count = ref(0)
.value属性访问实际值,适合简单的数据绑定。reactive() 函数const state = reactive({ count: 0 })
computed() 函数const doubleCount = computed(() => state.count * 2)
watch() 函数watch(count, (newValue, oldValue) => {
console.log(`count changed from ${oldValue} to ${newValue}`)
})
watchEffect() 函数watch(),但自动追踪依赖项并执行回调。watchEffect(() => {
console.log(`count is now ${count.value}`)
})
toRef() 和 toRefs()ref,便于在模板或逻辑中单独使用。const stateRef = reactive({ count: 0 })
const countRef = toRef(stateRef, 'count')
onBeforeMount(), onMounted(), onBeforeUpdate(), onUpdated(), onUnmounted() 等生命周期钩子onMounted(() => {
console.log('Component mounted.')
})
provide() 和 inject()// 祖先组件
provide('theme', 'dark')
// 子孙组件
const theme = inject('theme')
render()export default {
render() {
return h('div', {}, 'Hello World!')
}
}
在Vue 3中,引入了Composition API来提供一种更灵活和强大的方式来组织组件逻辑。其中,defineProps、defineEmits、defineExpose、defineSlots 和 defineOptions 是几个核心宏函数,用于定义组件的不同方面。
defineProps块中定义组件接收的属性(props)。它允许你指定每个prop的类型、默认值等。import { defineProps } from 'vue';
defineProps({
message: {
type: String,
required: true
},
count: Number
});
中不需要显式导入,直接使用即可,是编译时的语法糖。defineEmits块中声明组件可以向外发出的事件(emits)。它帮助你定义组件间通信的事件接口。import { defineEmits } from 'vue';
const emit = defineEmits(['update:modelValue']);
function updateValue(newValue) {
emit('update:modelValue', newValue);
}
中无需导入,直接使用,提供事件名称的类型检查。defineExpose中用于公开组件内部的一些方法或属性给使用该组件的父组件或其他外部环境。import { defineExpose } from 'vue';
const internalMethod = () => { /* 内部逻辑 */ };
defineExpose({
publicMethod: internalMethod
});
defineSlotsdefineSlots宏函数。Vue 3采用模板语法来处理插槽内容,如默认插槽、具名插槽等,通常不需要特殊声明。但在Composition API中,你可以直接通过useSlots()函数来访问插槽内容。useSlots作为替代):import { useSlots } from 'vue';
const slots = useSlots();
console.log(slots.default?.()); // 访问默认插槽
console.log(slots.namedSlot?.()); // 访问具名插槽
defineOptions块中定义组件的选项,如名称(name)、继承(inheritAttrs)、模型(options.model)等。import { defineOptions } from 'vue';
defineOptions({
name: 'MyComponent',
inheritAttrs: false
});
createApp()const app = createApp(App);
app.mount('#app');
createSSRApp()createApp类似,但针对SSR做了特别优化。import { createSSRApp } from 'vue';
import App from './App.vue';
export function createServerApp() {
return createSSRApp(App);
}
app.mount()app.mount('#app');
app.unmount()app.unmount();
app.component()app.component('MyComponent', MyComponent);
app.directive()app.directive('my-directive', {
mounted(el, binding, vnode) {
// 指令逻辑
}
});
app.use()app.use(myPlugin);
app.provide()inject访问。app.provide('service', myService);
app.runWithContext()app.versionapp.configapp.config.errorHandler:全局错误处理函数。app.config.warnHandler:全局警告处理函数。app.config.performance:开启性能追踪。app.config.compilerOptions:自定义Vue模板编译器选项。app.config.globalProperties:添加全局属性,使得所有组件都能访问。app.config.optionMergeStrategies: 自定义选项合并策略,用于控制Vue如何合并组件选项。