vue2与vue3的写法差距
vue2
执行方法需要加 this
export default {
data () {
return {
list: []
}
},
created () {
this.getData()
},
methods: {
getData () {
this .$api.get( 'topics' , null , r => {
console.log(r)
})
}
}
}
</script>
vue3语法
//父组件
<template>
<Foo :count="count" @onSubmit="inc" />
</template>
<script lang="ts" setup>
import { ref } from 'vue'
const count = ref<number>(0)
const inc = () :void => {
count.value++
}
</script>
//子组件
<template>
<div @click="onClick">{{count}}</div>
</template>
<script lang="ts" setup>
import { defineProps, defineEmits } from 'vue'
// 定义props属性
interface user{
count: Number
}
const props = defineProps<user>();
// 定义emit事件
interface event{
(e: onSubmit) : void
}
const emit = defineEmits<emit>();
const onClick=() : void=>{
emit('onSubmit', { val: props.foo })
}
</script>
react函数组件和类组件的差异
函数组件
function MessageThread() {
const [message, setMessage] = useState('');
const showMessage = () => {
alert('You said: ' + message);
};
const handleSendClick = () => {
setTimeout(showMessage, 3000);
};
const handleMessageChange = (e) => {
setMessage(e.target.value);
};
return <>
<input value={message} onChange={handleMessageChange} />
<button onClick={handleSendClick}>Send</button>
</>;
}
类组件
class main extends Components {
constructor(props){
super(props)
this.state={
name:"zs",
age:12
}
}
addage(){
return this.state.age+12
}
render(){
const flag=true
const list = [1, 2, 3]
return (
// jsx需要一个根元素
<div className="main">
<p>{this.state.name}</p>
<p>{this.state.age>18?'成年':'未成年'}</p>
<p>{this.addage.call(this)}</p>
{/* 三元表达式判断显示元素 */}
{
flag?
<p>元素1</p>
:
<p>元素2</p>
}
{/* 只能用map循环 */}
{list.map((item) => {
return <div key='item'>{item}</div>
})}
</div>
)
}
}
函数组件没有this指向问题,变量直接使用,方法的使用也无需通过this
onClick={handleSendClick}
类组件的方法需要手动绑定this 绑定this的方法有三种
01.
constructer(props){
this.handleclick=this.handleclick.bind(this);
};
02.
<button onClick={this.handleclick3}>button3</button>
handleclick3 = ()=>{
console.log('button3被点击了')
}//方法写成箭头函数形式
03.
绑定this的情况下还可以传递参数
onClick={(e)=>this.handleClick(e,aaa)}
onClick={this.handleClick.bind(this,aaa)}