在之前的文章中,小编和大家一起学习了对于Vue的根本语法和概念,包含组件、数据混入和插槽等。从明天开始,小编和大家一起学习Vue3中的新个性,也就是网上炒的铺天盖地的Composition-API,看看到底有什么神奇之处,咱们之前通过Vue写的代码,根本都是这样
Vue.createApp({ data(){ return { name:"" // 绑定根本数据类型数据 items:[1,2,3,4] // 绑定援用数据类型 } }, methods:{ handleClick(){ // 绑定按钮的点击函数 this.name = 'lilei' this.items.push(5) } }, template:` <div> <input v-model="name" /> <button @click="handleClick">减少</button> <ul> <li v-for="(item,index) of items" :key="index">{{item}}</li> </ul> </div> `}).mount('#root')
同样的代码,革新成setup函数的模式,就是这样
Vue.createApp({ template: `<div> <input v-model="name" /> <button @click="handleClick">减少</button> <ul> <li v-for="(item,index) of items" :key="index">{{item}}</li> </ul> </div>`, setup(){ let name="" let items = [1,2,3,4] const handleClick = () => { name = 'lilei' items.push(5) } return { name, items } }}).mount('#root')
这个时候咱们发现,不仅按钮点击事件不好用了,甚至控制台也会呈现正告,handleClick办法没有被注册,实际上这正是小编要和大家分享的三个点
一、控制台呈现的正告是因为在setup函数中没有返回对应的函数,在页面中应用的变量和函数,都须要在return的对象中,能力应用,至于网上说的其余的痛点,比方如何获取this还有组件之间传值,小编会在接下来的内容中相继更新。为了修复控制台的谬误,咱们能够把代码欠缺成这样
Vue.createApp({ template: `<div> <input v-model="name" /> <button @click="handleClick">减少</button> <ul> <li v-for="(item,index) of items" :key="index">{{item}}</li> </ul> </div>`, setup(){ let name="" let items = [1,2,3,4] const handleClick = () => { name = 'lilei' items.push(5) } return { name, items, handleClick } }}).mount('#root')
通过下面的改变,咱们发现控制台的谬误是不见了,然而点击按钮仍然没有反馈,这个时候咱们须要引入setup函数中对于根本数据类型和援用数据类型的绑定形式
二、根底数据类型响应式援用——ref
Vue.createApp({ template: `<div> <input v-model="name" /> <button @click="handleClick">减少</button> <ul> <li v-for="(item,index) of items" :key="index">{{item}}</li> </ul> </div>`, setup(){ // 通过数据解构的形式引入ref let { ref } = Vue // ref 解决根底类型的数据 // proxy 'lilei'变成 proxy({value:'lilei'})这样的一个响应式援用 let name=ref("") let items = [1,2,3,4] const handleClick = () => { // name = 'lilei' name.value = 'lilei' // 引入ref之后,数据格式产生扭转,批改内容的时候,也要相应的调整 items.push(5) } return { name, items, handleClick } }}).mount('#root')
三、援用数据类型响应式援用——reactive
Vue.createApp({ template: `<div> <input v-model="name" /> <button @click="handleClick">减少</button> <ul> <li v-for="(item,index) of items" :key="index">{{item}}</li> </ul> </div>`, setup(){ // 通过数据解构的形式引入reactive let { ref,reactive } = Vue // reactive 解决非根底类型的数据,常见的有Array和Object类型 // proxy [1,2,3,4]变成 proxy([1,2,3,4])这样的一个响应式援用 let name=ref("") let items = reactive([1,2,3,4]) const handleClick = () => { // name = 'lilei' name.value = 'lilei' // 引入ref之后,数据格式产生扭转,批改内容的时候,也要相应的调整 items.push(5) } return { name, items, handleClick } }}).mount('#root')
至此,咱们实现了一个从“传统”Vue写法,转向了Vue3中Composition-API的写法,在代码中还是有一些痛点,这个小编会在后续的文章中继续更新。
大家还能够扫描二维码,关注我的微信公众号,蜗牛全栈。