詳解vue3中setUp和reactive函數(shù)的用法
1 setUp的執(zhí)行時機
我們都知道,現(xiàn)在vue3是可以正常去使用methods的。
但是我們卻不可以在setUp中去調用methods中的方法。
為什么了???
我們先了解一下下面這兩個生命周期函數(shù),分別是:
beforeCreate 表示data 中的數(shù)據(jù)還沒有初始化,是不可以使用的
Created : data已經(jīng)被初始化了,可以使用
setUp在beforeCreate 和 Created 這兩個函數(shù)之間。
是不是就知道為啥setUp中不可以去調用methods中的方法了。
2.setUp中無法使用data中的數(shù)據(jù)和調用methods的方法
<script> export default { name: 'App', data:function(){ return { mess:"我是data" } }, methods:{ func(){ console.log("methods中的func") }, }, setup(){ console.log('this',this);//undefined this.func();//無法調用的哈 }, } </script>
3.setUp函數(shù)的注意點
(1)由于我們不能夠在setUp函數(shù)中使用data和methods.
所以vue為了避免我們的錯誤使用,直接將setUp函數(shù)中的this
修改成為了undefined
(2) setUp函數(shù)只能夠數(shù)同步的,不能夠是異步的哈。
就是說你不能夠這樣操作
async setup(){
},
這樣會導致界面空白哈
4 Vue3中的reactive
在Vue2中響應式數(shù)據(jù)是通過de fineProperty來實現(xiàn)的.
而在Vue3中響應式數(shù)據(jù)是通過ES6的Proxy來實現(xiàn)的
reactive需要的注意點
reactive參數(shù)必須是對象(json/arr)
如果給reactive傳遞了其它對象
默認情況下修改對象,界面不會自動更新
如果想更新,可以通過重新賦值的方式
5 reactive傳入字符串數(shù)據(jù)不跟新
<template> <div> <div> <li>{{str}}</li> <button @click="func1">按鈕</button> </div> </div> </template> <script> import {reactive} from 'vue' export default { name: 'App', setup(){ // reactive 的本質就是傳入的數(shù)據(jù)包裝成一個proxy對象 // 由于在創(chuàng)建的時候,傳遞的不是一個對象,那么將不會實現(xiàn)響應式。 let str=reactive(123) function func1(){ console.log(str);//123 str=666; } return {str,func1 } }, } </script>
我們發(fā)現(xiàn)點擊按鈕的時候,視圖并沒有更新。
因為我們傳不是一個對象.如果想跟新視圖。
應該使用ref函數(shù)
6 reactive傳入數(shù)組
<template> <div> <div> <li>{{arr}}</li> <button @click="func1">按鈕</button> </div> </div> </template> <script> import {reactive} from 'vue' export default { name: 'App', setup(){ let arr=reactive([{name:'張三',age:19},{name:'李四',age:39}]) function func1(){ arr[0].name="我是張三的哥哥" } return {arr,func1 } }, } </script>
7 reactive傳入其他對象的跟新方式
<template> <div> <div> <li>{{sate.time}}</li> <button @click="func1">按鈕</button> </div> </div> </template> <script> import {reactive} from 'vue' export default { name: 'App', setup(){ let sate=reactive({ time:new Date() }) function func1(){ //傳入的是其他對象,直接跟新 sate.time="2021年-6月-9日"; } return {sate,func1 } }, } </script>
以上就是vue3 setUp和reactive函數(shù)詳細講解的詳細內(nèi)容,更多關于vue3 setUp和reactive函數(shù)的資料請關注腳本之家其它相關文章!
相關文章
Vue-router 類似Vuex實現(xiàn)組件化開發(fā)的示例
本篇文章主要介紹了Vue-router 類似Vuex實現(xiàn)組件化開發(fā)的示例,具有一定的參考價值,有興趣的可以了解一下2017-09-09Vue引入使用localforage改進本地離線存儲方式(突破5M限制)
這篇文章主要介紹了Vue引入使用localforage改進本地離線存儲方式(突破5M限制),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03vue3.0搭配.net core實現(xiàn)文件上傳組件
這篇文章主要介紹了vue3.0搭配.net core實現(xiàn)文件上傳組件,幫助大家開發(fā)Web應用程序,完成需求,感興趣的朋友可以了解下2020-10-10