1. 自定义指令
Vue.js允许我们注册自定义指令,用于对DOM元素进行底层操作。
自定义指令示例
这段文字会改变颜色
// 注册全局指令
app.directive('focus', {
mounted(el) {
el.focus()
}
})
app.directive('highlight', {
mounted(el, binding) {
el.style.color = binding.value
},
updated(el, binding) {
el.style.color = binding.value
}
})
2. 渲染函数
Vue.js提供了渲染函数,允许我们使用JavaScript来创建虚拟DOM。
const app = Vue.createApp({
render() {
return Vue.h('div', {
class: 'container'
}, [
Vue.h('h1', '标题'),
Vue.h('p', '内容')
])
}
})
3. 过渡和动画
Vue.js提供了强大的过渡和动画系统。
过渡示例
这是一个过渡效果
<transition name="fade">
<p v-if="show">这是一个过渡效果</p>
</transition>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
4. 混入
混入是一种分发Vue组件中可复用功能的灵活方式。
const myMixin = {
created() {
this.hello()
},
methods: {
hello() {
console.log('hello from mixin!')
}
}
}
const app = Vue.createApp({
mixins: [myMixin]
})
5. 插件
插件通常用来为Vue添加全局功能。
const myPlugin = {
install(app, options) {
app.config.globalProperties.$myMethod = () => {
console.log('This is a plugin method')
}
}
}
const app = Vue.createApp({})
app.use(myPlugin)
6. 组合式API
组合式API是Vue 3中新增的特性,提供了更好的代码组织方式。
组合式API示例
计数: {{ count }}
import { ref, computed } from 'vue'
export default {
setup() {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
function decrement() {
count.value--
}
return {
count,
doubleCount,
increment,
decrement
}
}
}
7. 响应式系统
深入了解Vue.js的响应式系统工作原理。
import { reactive, watch } from 'vue'
const state = reactive({
count: 0
})
watch(() => state.count, (newValue, oldValue) => {
console.log('count changed:', oldValue, '->', newValue)
})
高级特性使用建议
- 合理使用自定义指令处理DOM操作
- 使用渲染函数处理复杂的动态渲染
- 善用过渡和动画提升用户体验
- 使用组合式API优化代码组织
练习
尝试实现以下高级功能:
- 创建一个自定义指令实现图片懒加载
- 使用组合式API重构一个现有组件
- 实现一个复杂的过渡动画效果
- 开发一个Vue插件