移除了 $children
$children 实例 property 已从 Vue 3.0 中移除,不再支持。
2.x 语法
在 2.x 中,开发者可以使用 this.$children 直接访问当前实例的子组件:
<template>
<div>
<img alt="Vue logo" src="./assets/logo.png">
<my-button>Change logo</my-button>
</div>
</template>
<script>
import MyButton from './MyButton'
export default {
components: {
MyButton
},
mounted() {
console.log(this.$children) // [VueComponent]
}
}
</script>
3.x 更新
在 3.x 中,$children property 已移除,不再支持。如果你需要访问子组件实例,我们建议使用 $refs。
ref attribute 相当于为子组件或 HTML 元素指定引用 ID。
<input ref="input" />
这里 $ref 相当于获取自身的节点
const app = Vue.createApp({}) app.component('base-input', { template: ` <input ref="input" /> `, methods: { focusInput() { this.$refs.input.focus() } }, mounted() { this.focusInput() } })
此外,还可以向组件本身添加另一个 ref,并使用它从父组件触发 focusInput 事件:
父组件调用子组件方法
<base-input ref="usernameInput"></base-input> this.$refs.usernameInput.focusInput()
官方建议 避免在模板或计算属性中访问 $refs,$refs 只会在组件渲染完成之后生效。
自定义指令
2.x 语法
在 Vue 2,自定义指令是通过使用下面列出的钩子来创建的,这些钩子都是可选的
- bind - 指令绑定到元素后发生。只发生一次。
- inserted - 元素插入父 DOM 后发生。
- update - 当元素更新,但子元素尚未更新时,将调用此钩子。
- componentUpdated - 一旦组件和子级被更新,就会调用这个钩子。
- unbind - 一旦指令被移除,就会调用这个钩子。也只调用一次。
<p v-highlight="'yellow'">高亮显示此文本亮黄色</p> Vue.directive('highlight', { bind(el, binding, vnode) { el.style.background = binding.value } })
3.x 语法
然而,在 Vue 3 中,我们为自定义指令创建了一个更具凝聚力的 API。正如你所看到的,它们与我们的组件生命周期方法有很大的不同,即使我们正与类似的事件钩子,我们现在把它们统一起来了:
- bind → beforeMount
- inserted → mounted
- beforeUpdate:新的!这是在元素本身更新之前调用的,很像组件生命周期钩子。
- update → 移除!有太多的相似之处要更新,所以这是多余的,请改用
updated。 - componentUpdated → updated
- beforeUnmount:新的!与组件生命周期钩子类似,它将在卸载元素之前调用。
- unbind -> unmounted
最终 API 如下:
const MyDirective = { beforeMount(el, binding, vnode, prevVnode) {}, mounted() {}, beforeUpdate() {}, // 新 updated() {}, beforeUnmount() {}, // 新 unmounted() {} }
const app = Vue.createApp({}) app.directive('highlight', { beforeMount(el, binding, vnode) { el.style.background = binding.value } })
人生很漫长,或许我只是你人生中微不足道的一小段,只是你人生中的惊鸿一瞥。
浙公网安备 33010602011771号