vue2→vue3

2023-02-03  本文已影响0人  欢西西西

文档

1. 数据响应式的变化

从Object.defineProperty到Proxy

<script setup>
    import { ref, reactive, computed, watch } from 'vue'
    
    // 利用ref和reactive自己去设置哪些对象需要响应式
    const firstName = ref('John')
    const lastName = ref('Doe')
    const fullName = computed(() => firstName.value + ' ' + lastName.value)

    const info = reactive({ id: '1212', title: 'w' });
    watch(info, (newValue, oldValue)=>{}) // 所有属性修改都会触发
    watch(()=>info.title, (newValue, oldValue)=>{}) // 只监听title属性
</script>

2. composition api

3. 可以创建多个Vue实例

这样可以在一个大型页面中,利用vue只控制其中的一部分;可以创建多个实例分别挂载到需要的元素上去

4. 生命周期

<script setup>
    import {
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted
    } from 'vuex';

    // 钩子名前面都加on
    // 没有 beforeCreate和created
    // beforeDestroy 和 Destroyed改为了 onBeforeUnmount 和 onUnmounted
    onBeforeMount(() => {
        // 虚拟dom树与数据完成双向绑定,触发beforeMount
    });
    onMounted(() => {
        // 创建真实dom后
    });
</script>

5. 父子组件传值

<script setup>
    // 在没有使用 <script setup> 的组件中,props依然可以通过选项来设置
    // defineProps(['title', 'qty']); // 也可以使用数组
    defineProps({
        title: {type: String, default: '详情'},
        qty: [String, Number]
    })
</script>
// 父组件
<script setup>
    import { ref } from 'vue'
    const child = ref(null); // 拿到注册了ref='child'的组件
    child.value.reset(); // 调用子组件的方法
</script>
// 子组件
<script setup>
    const reset = () => { };
    defineExpose({ // 显式指定在 <script setup> 组件中要暴露出去的属性
        reset
    });
</script>

在vue2中,父组件可以通过this.$refs[refName]拿到child组件后直接调它的方法,对于子组件来说,哪些方法被调用了是不透明的。通过defineExpose显式指定导出,就能明确哪些方法是开放给外部可用的,而哪些方法只希望内部使用

<script setup>
    // defineEmits和defineProps不需要导入,自动地在 <script setup> 中可用

    const emit = defineEmits(['success']);
    const onSuccess = () => {
        // 在子组件中通知父组件,
        // this.$emit('success',{ action: 'edit' }) // vue2的写法
        emit('success', { action: 'edit' });
    }
</script>

6. 状态管理 Pinia

上一篇 下一篇

猜你喜欢

热点阅读