对组件使用双向绑定时,有2种方式
value
和事件 input
。<ChildComponent :value="myTitle" @input="myTitle = $event" />
<ChildComponent v-model="myTitle" />
<ChildComponent :title="myTitle" @update:title="myTitle = $event" />
<ChildComponent :title.sync="myTitle" />
做了修改,
v-model
绑定的属性 value
--> modelValue
,事件input
--> update:modelValue
<ChildComponent :modelValue="myTitle" @update:modelValue="myTitle = $event" />
<ChildComponent v-model="myTitle" />
v-model
的参数替代。<ChildComponent :title="myTitle" @update:title="myTitle = $event" />
<ChildComponent v-model:title="myTitle" />
v-model
修饰符。官网参考
<template>
<ChildComponent v-model.cap="data1" v-model:title.capitalize="data2" />
template>
<script setup>
import { ref, reactive } from "vue";
import ChildComponent from "./components/ChildComponent.vue";
const data1 = ref(false);
const data2 = reactive({ a: 1, b: 2 });
script>
<script setup>
const props = defineProps({
modelValue: Boolean,
title: Object,
modelModifiers: { default: () => ({}) }, // v-model 默认的修饰符对象。
titleModifiers: { default: () => ({}) }, // v-model 有参数时,修饰符对象为 arg + "Modifiers"
});
console.log(props.modelModifiers); // {cap: true}
console.log(props.titleModifiers); // {capitalize: true}
script>
vue2 和 vue3 都不推荐同时使用 v-if
和 v-for
。
优先级:
v-for
> v-if
。官网参考v-for
< v-if
。官网参考当使用进行
v-for
循环时:
key
需要放到子元素上。key
需要放到
上。
<template v-for="todo in todos">
<li :key="todo.name">{{ todo.name }}li>
template>
<template v-for="todo in todos" :key="todo.name">
<li>{{ todo.name }}li>
template>
当使用 v-if v-else-if v-else
分支的时:
key
才能保证唯一。key
值,因为会自动给每个分支一个唯一的key
。使用如下代码举例
<template>
<div>
<div v-if="showAccount">
<label for="">账号label>
<input type="text" name="" id="" />
div>
<div v-else>
<label for="">密码label>
<input type="text" name="" id="" />
div>
<button @click="showAccount = !showAccount">切换button>
div>
template>
vue2 的效果
vue3 的效果
vue2 想实现一样的效果,就得给 v-if v-else
分支添加唯一 key
才行。
vue3
现在允许组件出现多个根节点。
<template>
<div>
<h1>标题1h1>
<h2>标题2h2>
div>
template>
<template>
<h1>标题1h1>
<h2>标题2h2>
template>
官网参考
是 vue3 的内置组件。该组件的子元素将被渲染到指定 DOM 元素中(使用 to
指定)。
to
可以是 css 选择器字符串,也可以是 DOM 元素对象。
经典例子:Dialog 弹窗一般都会渲染到 body
元素下。
<template>
<div>
<button @click="open = true">Open Modalbutton>
<Teleport to="body">
<div v-if="open">
<p>dialogp>
<button @click="open = false">Closebutton>
div>
Teleport>
div>
template>
<script setup>
import { ref } from "vue";
const open = ref(false);
script>
参考这篇文章
以上。