詳解vue3中setUp和reactive函數(shù)的用法
1 setUp的執(zhí)行時(shí)機(jī)
我們都知道,現(xiàn)在vue3是可以正常去使用methods的。但是我們卻不可以在setUp中去調(diào)用methods中的方法。為什么了???我們先了解一下下面這兩個(gè)生命周期函數(shù),分別是:beforeCreate 表示data 中的數(shù)據(jù)還沒有初始化,是不可以使用的Created : data已經(jīng)被初始化了,可以使用setUp在beforeCreate 和 Created 這兩個(gè)函數(shù)之間。是不是就知道為啥setUp中不可以去調(diào)用methods中的方法了。
2.setUp中無法使用data中的數(shù)據(jù)和調(diào)用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();//無法調(diào)用的哈 },}</script>
3.setUp函數(shù)的注意點(diǎn)
(1)由于我們不能夠在setUp函數(shù)中使用data和methods.所以vue為了避免我們的錯(cuò)誤使用,直接將setUp函數(shù)中的this修改成為了undefined
(2) setUp函數(shù)只能夠數(shù)同步的,不能夠是異步的哈。
就是說你不能夠這樣操作async setup(){ },這樣會導(dǎo)致界面空白哈
4 Vue3中的reactive
在Vue2中響應(yīng)式數(shù)據(jù)是通過de fineProperty來實(shí)現(xiàn)的.而在Vue3中響應(yīng)式數(shù)據(jù)是通過ES6的Proxy來實(shí)現(xiàn)的
reactive需要的注意點(diǎn)reactive參數(shù)必須是對象(json/arr)如果給reactive傳遞了其它對象默認(rèn)情況下修改對象,界面不會自動更新如果想更新,可以通過重新賦值的方式
5 reactive傳入字符串?dāng)?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 的本質(zhì)就是傳入的數(shù)據(jù)包裝成一個(gè)proxy對象 // 由于在創(chuàng)建的時(shí)候,傳遞的不是一個(gè)對象,那么將不會實(shí)現(xiàn)響應(yīng)式。 let str=reactive(123) function func1(){ console.log(str);//123 str=666; } return {str,func1 } },}</script>
我們發(fā)現(xiàn)點(diǎn)擊按鈕的時(shí)候,視圖并沒有更新。因?yàn)槲覀儌鞑皇且粋€(gè)對象.如果想跟新視圖。應(yīng)該使用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ù)詳細(xì)講解的詳細(xì)內(nèi)容,更多關(guān)于vue3 setUp和reactive函數(shù)的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 使用 kind 和 Docker 啟動本地的 Kubernetes環(huán)境2. ASP基礎(chǔ)入門第八篇(ASP內(nèi)建對象Application和Session)3. XML入門精解之結(jié)構(gòu)與語法4. Idea如何去除Mapper警告方法解析5. idea設(shè)置自動導(dǎo)入依賴的方法步驟6. IntelliJ IDEA設(shè)置編碼格式的方法7. idea設(shè)置代碼格式化的方法步驟8. idea自定義快捷鍵的方法步驟9. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法10. idea重置默認(rèn)配置的方法步驟
