Vue2与Vue3 最大的区别 — Vue2使用选项类型API(Options API)对比Vue3合成型API(Composition API)
作用: 聚合代码 & 逻辑重用
1. 使用 reactive 绑定数据
<template>
<div>
<h1>使用 reactive 绑定数据</h1>
<p>{
{
state.msg}}</p>
<p>{
{
info}}</p>
<p>
<button @click="changeMsg">changeMsg</button>
</p>
</div>
</template>
<script>
// Hooks 编程,在 vue 中导入对应的函数方法,面向函数式进行编程
// Vue-composition-API 这里就是Vue2与Vue3 最大的区别 — Vue2使用选项类型API(Options API)对比Vue3合成型API(Composition API)
import {
defineComponent, reactive } from "vue";
export default defineComponent({
name: 'test1',
setup() {
// setup钩子函数
// 使用响应式函数reactive构建proxy响应式对象state
const state = reactive({
msg: '时光'
})
console.log(state); // state对象是一个proxy拦截对象
let info = 'hello'; // info是一个普通对象,修改后不会被proxy拦截,进而页面也不会动态更新
const changeMsg = () => {
// 在外边定义methods
state.msg = '时光,你好'
info = 'hello,你好'
}
return {
// 使用时,要把对象return出去,才能在template中使用
state,
info,
changeMsg
}
}
})
</script>
2. setup()函数 完成父子通信
1. setup(props)第一个参数props
setup函数接收props作为其第一个参数,props对象是响应式的(单向的父—>子),watchEffect或watch会观察和响应props的更新。不要对props对象进行解构,那样会失去响应性。在开发过程中,props对象对用户空间代码时不可变的,用户尝试修改props时会触发警告
案例1:props作为setup的第一个参数
// 父组件 Home.vue
<template>
<div class="home">
<About :name="sendData"/>
</div>
</template>
<script>
import {
ref} from 'vue';
import About from './About'
export default{
components:{
About,
},
setup(){
const sendData = ref('这世界很酷');
return {
sendData
}
}
}
</script>
// 子组件About.vue
<template>
<div class=