钩子
1. setup 函数还要在beforeCreate()钩子之前执行
2. setup里面没有 beforeCreate和Created两个钩子
3. setup中的钩子加on
4. update 阶段:数据改变会触发此阶段,数据改变会重新渲染虚拟 DOM 给真实 DOM 打补丁
ref
用于获取模板中的元素(真实的dom元素或者某个组件的对象)
- 创建空的ref对象:const myRef = ref(null)
- 建立关联:<h1 ref="myRef">12</h1>
- 在onMounted()钩子中使用:myRef.value
代码:
<template>
<div>
<h1 ref="myRef">123</h1>
<my-demo ref="myDemoRef"></my-demo>
</div>
</template>
<script>
import MyDemo from '../components/HelloWorld.vue'
import { onMounted, ref } from 'vue'
export default {
components: {
MyDemo
},
setup () {
// 创建 ref
const myRef = ref(null)
const myDemoRef = ref(null)
onMounted(() => {
console.log(myRef.value) // DOM元素
console.log(myDemoRef.value) // 组件对象
})
return {
myRef,
myDemoRef
}
}
}
</script>