-
Composition API(组合式API):Vue 3引入了Composition API,它允许开发者通过将相关逻辑组合成自定义函数来构建组件,取代了Vue 2中的Options API。这使得代码更可读、维护性更好。
示例代码:
<template> <div> <p>{{ count }}</p> <button @click="increment">增加</button> </div> </template> <script> import { ref } from 'vue'; export default { setup() { const count = ref(0); function increment() { count.value++; } return { count, increment }; } }; </script>
-
Teleport(传送门):Teleport是Vue 3中引入的新特性,它允许您将组件的内容渲染到DOM中的其他位置。这对于创建模态框、弹出菜单等功能非常有用。
示例代码:
<template> <div> <button @click="showModal = true">打开模态框</button> <teleport to="body" v-if="showModal"> <div class="modal"> <h2>模态框标题</h2> <p>模态框内容</p> <button @click="showModal = false">关闭</button> </div> </teleport> </div> </template> <script> import { ref } from 'vue'; export default { setup() { const showModal = ref(false); return { showModal }; } }; </script>
-
Fragments(片段):在Vue 3中,您可以使用Fragments来包裹多个根级元素,而无需使用额外的DOM元素。这样可以减少不必要的嵌套层级。
示例代码:
<template> <> <h1>标题</h1> <p>段落1</p> <p>段落2</p> </> </template>
-
全局API的修改和移除:Vue 3对全局API进行了修改和移除。例如,
Vue.component
现在变成了app.component
;Vue.filter
现在变成了app.config.globalProperties.$filter
;Vue.mixin
现在变成了app.mixin
。这样的修改使代码更加一致和易于理解。
示例代码:
// 在Vue 2中,注册全局组件使用 Vue.component
Vue.component('my-component', {
// 组件的定义
});
// 在Vue 3中,注册全局组件使用 app.component
const app = Vue.createApp({});
app.component('my-component', {
// 组件的定义
});
// 在Vue 2中,注册全局过滤器使用 Vue.filter
Vue.filter('my-filter', function(value) {
// 过滤器的逻辑
return newValue;
});
// 在Vue 3中,注册全局过滤器使用 app.config.globalProperties.$filter
const app = Vue.createApp({});
app.config.globalProperties.$filter = function(value) {
// 过滤器的逻辑
return newValue;
};
// 在Vue 2中,使用全局混入使用 Vue.mixin
Vue.mixin({
// 混入的逻辑
});
// 在Vue 3中,使用全局混入使用 app.mixin
const app = Vue.createApp({});
app.mixin({
// 混入的逻辑
});
5.引入了更好的Tree-shaking支持:Vue 3采用了更好的Tree-shaking技术,减少了无用代码的体积,提升了应用的性能。
示例代码:
<template>
<div>
<custom-component v-if="showCustomComponent" />
<button @click="toggleComponent">Toggle Component</button>
</div>
</template>
<script>
import { ref } from 'vue';
import CustomComponent from './CustomComponent.vue';
export default {
components: {
CustomComponent
},
setup() {
const showCustomComponent = ref(false);
function toggleComponent() {
showCustomComponent.value = !showCustomComponent.value;
}
return {
showCustomComponent,
toggleComponent
};
}
};
</script>
在这个示例中,我们只有在showCustomComponent
为true
时才会渲染CustomComponent
组件。如果showCustomComponent
为false
,CustomComponent
将不会被引入到最终的打包代码中。