• Vue 3 相对于 Vue2,模板和组件的一些变化


    1,模板的变化

    1,v-model

    vue2

    对组件使用双向绑定时,有2种方式

    1. v-model,默认会绑定属性 value 和事件 input
    <ChildComponent :value="myTitle" @input="myTitle = $event" />
    
    <ChildComponent v-model="myTitle" />
    
    • 1
    • 2
    • 3
    1. async 修饰符
    <ChildComponent :title="myTitle" @update:title="myTitle = $event" />
    
    <ChildComponent :title.sync="myTitle" />
    
    • 1
    • 2
    • 3

    vue3

    做了修改,

    1. v-model 绑定的属性 value --> modelValue,事件input --> update:modelValue
    <ChildComponent :modelValue="myTitle" @update:modelValue="myTitle = $event" />
    
    <ChildComponent v-model="myTitle" />
    
    • 1
    • 2
    • 3
    1. 删除了async 修饰符,该功能由 v-model 的参数替代。
    <ChildComponent :title="myTitle" @update:title="myTitle = $event" />
    
    <ChildComponent v-model:title="myTitle" />
    
    • 1
    • 2
    • 3
    1. 允许自定义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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    
    <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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2,v-if 和 v-for

    vue2 和 vue3 都不推荐同时使用 v-ifv-for

    优先级:

    3,key

    v-for

    当使用