一、模板引用
当我们需要访问底层dom元素时,可以使用ref,它类似于原生JS里的'id'.可以直接通过ref拿到这个元素或者组件,当定义一个值来存放这个属性字段时,我们需要声明一个同名的 ref:
<script setup>
//引入ref和生命周期
import { ref, onMounted } from 'vue'
// 声明一个 ref 来存放该元素的引用
// 必须和模板里的 ref 同名
const input = ref(null)
//组件挂载完成后自动锁定光标在这个input框上
onMounted(() => {
input.value.focus()
})
</script>
<template>
<input ref="input" />
</template>
v-for
中的模板引用
在v-for中使用模板引用时,对应的ref是一个数组,它将在元素循环后包含整个循环的所有元素
<script setup>
import { ref, onMounted } from 'vue'
const list = ref([
/* ... */
])
const itemRefs = ref([])
onMounted(() => console.log(itemRefs.value))
</script>
<template>
<ul>
<li v-for="item in list" ref="itemRefs">
{{ item }}
</li>
</ul>
</template>
二、组件引用
在Vue2中,使用组件需要先引入,再components中定义再使用,Vue3中,只要是在<script setup>中引入的子组件就可以直接使用
<script setup>
import ButtonCounter from './ButtonCounter.vue'
</script>
<template>
<h1>Here is a child component!</h1>
<ButtonCounter />
</template>
在Vue3中,组件传值有一点小小的变化,子组件接收父组件传来的值时,需要使用definePops 这个方法,defineProps
是一个仅 <script setup>
中可用的编译宏命令,并不需要显式地导入
父传子
父组件内容:
<template>
<div class="home">
<HelloWorld :index="num" /> //子组件
</div>
</template>
子组件接收:
<script setup>
defineProps(['num'])
</script>
<template>
<h4>{{ num}}</h4>
</template>
在实际应用中,我们可能在父组件中的可能是一个数组,这时候我们结合v-for循环做渲染
const posts = ref([
{ id: 1, title: '数据一' },
{ id: 2, title: '数据二' },
{ id: 3, title: '数据三' }
])
<BlogPost
v-for="post in posts"
:key="post.id"
:title="post.title"
/>
子传父
这里用到defineEmits宏,定义一个值存放
const emit = defineEmits(["updateNum"]);
写一个方法携带这个值做传递
<script setup>
const emit = defineEmits(['enlarge-text'])
emit('enlarge-text')
</script>