Ps:本人习惯使用setup语法糖的形式
is
在V3中,is属性用于动态组件的渲染,这个与V2中的用法类似,但是也有一些细微的差距,is属性允许你根据条件的动态渲染不同的组件或者HTML标签。
<template>
<div>
<!-- 动态渲染组件 -->
<component :is="currentComponent"></component>
<!-- 动态渲染HTML标签 -->
<component :is="currentTag">
动态标签内容
</component>
<!-- 切换按钮 -->
<button @click="toggleComponent">切换组件</button>
<button @click="toggleTag">切换标签</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
// 定义动态的组件和标签
const currentComponent = ref('ComponentA');
const currentTag = ref('div');
// 切换组件的方法
const toggleComponent = () => {
currentComponent.value = currentComponent.value === 'ComponentA' ? 'ComponentB' : 'ComponentA';
};
// 切换标签的方法
const toggleTag = () => {
currentTag.value = currentTag.value === 'div' ? 'h1' : 'div';
};
</script>
key
Vue3中key是一个常用的内置组件,通常用于确保Vue能够正确的管理和渲染元素或者组件列表。key属性的作用是在更新虚拟DOM时为每一个元素或者组件分配的唯一标识,以优化渲染性能和正确性。
使用场景一:
列表渲染
<template>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.text }}
</li>
</ul>
</template>
<script setup>
import { ref } from 'vue';
const items = ref([
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' }
]);
</script>
使用场景二:
强制组件重新渲染
<template>
<component :is="currentComponent" :key="currentKey"></component>
<button @click="toggleComponent">切换组件</button>
</template>
<script setup>
import { ref } from 'vue';
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
const currentComponent = ref('ComponentA');
const currentKey = ref(0);
const toggleComponent = () => {
currentComponent.value = currentComponent.value === 'ComponentA' ? 'ComponentB' : 'ComponentA';
currentKey.value += 1; // 改变 key 强制重新渲染组件
};
</script>
ref
在Vue3中,ref是一个非常重要的内置属性,用于获取和操作DOM元素或者子组件的实例。ref允许你在模版中给某个元素或组件添加一个标识,然后在组件的脚本部分通过该标识直接访问该元素或组件的实例。从而进行一些操作,比如聚焦输入框,调用子组件的方法等。
使用场景一:
获取DOM元素:
<template>
<input ref="inputElement" type="text" />
<button @click="focusInput">聚焦输入框</button>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const inputElement = ref(null);
const focusInput = () => {
inputElement.value.focus();
};
// 如果需要在组件挂载后立即聚焦
onMounted(() => {
inputElement.value.focus();
});
</script>
使用场景二:
获取子组件的实例
<!-- 子组件 ChildComponent.vue -->
<template>
<div>子组件内容</div>
</template>
<script setup>
const someMethod = () => {
console.log('子组件的方法被调用');
};
// 通过 defineExpose 公开的方法和数据可以在父组件中通过 ref 访问
defineExpose({
someMethod
});
</script>
<!-- 父组件 -->
<template>
<ChildComponent ref="childComponent" />
<button @click="callChildMethod">调用子组件方法</button>
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const childComponent = ref(null);
const callChildMethod = () => {
childComponent.value.someMethod();
};
</script>