阅读此帖时建议先阅读 带你体验Vue2和Vue3开发组件有什么区别
一、建立data
vue2
data()
{
return{
name:'',
age:''
}
}
vue3
import {reactive} from 'vue'
setup(){
const state = reactive({
name:'',
age:''
})
retrun {state}
}
二、methods编写
vue2
methods:{
//登录
login(){
}
}
vue3
setup(){
const login = () =>{
//登录
}
return {login}
}
三、生命周期 mounted
vue2
mounted(){
console.log('组件已挂载')
}
vue3
import {reactive,onMounted} from 'vue'
setup(){
onMounted(() => {
console.log('组件已挂载')
})
}
四、计算属性 computed
vue2
computed:{
lowerCaseName(){
return this.name.toLowerCase();
}
}
vue3
import {reactive,computed} from 'vue'
setup(){
const state = reactive({
name:'',
age:''
lowerCaseName: computed (() => state.name.toLowerCase())
})
}
五、接收props
vue2
mounted(){
console.log('title:' + this.title);
}
vue3
setup(props){
onMounted(() => {
console.log('title:' + props.title);
})
}
六、事件 emit
vue2
login(){
this.$emit('login', {
name: this.name,
age: this.age
})
}
vue3
setup(props,{emit}){
const login = () =>{
emit('login', {
name: state.name,
age: state.age
})
}
}
总结:不同点共分为以下6点
1、建立data
2、methods编写
3、生命周期 mounted
4、计算属性 computed
5、接收 props
6、事件 emit
最后特此鸣谢:三钻作者