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 的使用
生命周期函数
- vue3没有 created,beforeCreated,beforeDestory,destoryed
- 取代 beforeDestory,destoryed 的是 onBeforeUnmount ,onUnmounted
- 其他的生命周期函数都要在 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>