Vue2过渡Vue3的一些注意点

Vue2 过渡 Vue3

定义属性和方法 组合式API
<script lang="ts" setup>

import { reactive ,ref } from 'vue'

// ref 声明普通变量
const name =ref('小王')
const updateName =()=>{
    name.value = '小王王'
}

// reactive 声明对象属性
const objRef = ref({
    name:"小李",
    age:189
})
const updateObjRef =()=>{
objRef.value.name='小丽丽'
}

// reactive 声明对象属性
const obj = reactive({
    name:'小马',
    age:18
})
const updateObj =()=>{
    obj.name='小马马'
}


</script>

用 reactive 定义对象的时候,想要获取对象的属性,只需要 obj.name 即可拿到

使用 ref 定义对象也是可以的,但是要获取对象的属性的时候,需要 obj.value.name 这种格式

router

在这里插入图片描述

// vue3 使用 router
import {useRoute,useRouter} from "vue-router"
const route = useRoute()
const router = useRouter()

const init=()=>{
console.log('当前的路由路径是',route.path);
setTimeout(()=>{
    router.push("home")
},5000)
}

init()

vue2 的 this.$route

在这里插入图片描述

vue3 的 route 是 proxy 代理

在这里插入图片描述

定义全局方法和变量

vue 定义与使用 在 main.js 中

// vue2 全局方法的定义

const Utils ={
    add:(value)=>{
        return value +1
    }
}
Vue.prototype.Utils = Utils


// vue2 全局方法的使用

let val =123
this.Utils.add(val)



// vue3 全局方法的定义
import {createApp} from 'vue'
import App from './App.vue'
const app = createApp(App)

const Utils ={
    add:(value)=>{
        return value +1
    }
}

app.config.globalProperties.Utils = Utils

// vue3 全局方法的使用
import { getCurrentInstance } from 'vue'
const {proxy} =getCurrentInstance()

let val =123
proxy.Utils.add(test)

watch 的使用

在这里插入图片描述

生命周期函数
  1. vue3没有 created,beforeCreated,beforeDestory,destoryed
  2. 取代 beforeDestory,destoryed 的是 onBeforeUnmount ,onUnmounted
  3. 其他的生命周期函数都要在 vue2 的基础上加上 on

在这里插入图片描述

父子组件方法属性调用

子组件

<template>
<button @click="handleFather"></button>
  </template>
  
<script lang="ts" setup>


import { ref,defineProps,defineExpose} from "vue"

const emit =defineEmits()
const props =defineProps({
    msg:{
        type:String,
        default:''
    }
})

const msg2 =ref("")
const ParentOpSon = (parentMsg:any)=>{
    msg2.value=parentMsg
}

const handleFather =()=>{
    emit('getData',"这里是传递的参数")
}

defineExpose({
    ParentOpSon
})
</script>
  
<style lang="scss" scoped></style>

父组件

<template>
<Son ref="sonRef" :msg="myMsg" @opParent="parentMethod" @handleFather="getData"></Son>

</template>

<script lang="ts" setup>

import Son from './test.vue'
import { ref} from "vue"

// 子组件绑定的 ref 需要声明
const sonRef = ref()
// 子组件的 prop
const myMsg = ref("hello")
// 使用子组件的方法
const parentMethod =()=>{
    sonRef.value.ParentOpSon('123')
}

// 子组件要调用的方法
const getData=(val:any)=>{
console.log(val);

}

</script>

<style lang="scss" scoped>
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值