vue3函数setUp和reactive函数详细讲解

1 setUp的执行时机 我们都知道,现在vue3是可以正常去使用methods的。 但是我们却不可以在setUp中去调用methods中的方法。 为什么了??? 我们先了解一下下面这两个生命周期函数,分别是: beforeCreate 表示data 中的数据还没有初始化,是不可以使用的 Created : data已经被初始化了,可以使用 setUp在beforeCreate 和 Created 这两个函数之间。 是不是就知道为啥setUp中不可以去调用methods中的方法了。 2.setUp中无法使用data中的数据和调用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函数的注意点 (1)由于我们不能够在setUp函数中使用data和methods. 所以vue为了避免我们的错误使用,直接将setUp函数中的this 修改成为了undefined (2) setUp函数只能够数同步的,不能够是异步的哈。 就是说你不能够这样操作 async setup(){ }, 这样会导致界面空白哈 4 Vue3中的reactive 在Vue2中响应式数据是通过de fineProperty来实现的. 而在Vue3中响应式数据是通过ES6的Proxy来实现的 reactive需要的注意点 reactive参数必须是对象(json/arr) 如果给reactive传递了其它对象 默认情况下修改对象,界面不会自动更新 如果想更新,可以通过重新赋值的方式 5 reactive传入字符串数据不跟新 <template> <div> <div> <li>{{str}}</li> <button @click="func1">按钮</button> </div> </div> </template> <script> import {reactive} from 'vue' export default { name: 'App', setup(){ // reactive 的本质就是传入的数据包装成一个proxy对象 // 由于在创建的时候,传递的不是一个对象,那么将不会实现响应式。 let str=reactive(123) function func1(){ console.log(str);//123 str=666; } return {str,func1 } }, } </script>

我们发现点击按钮的时候,视图并没有更新。
因为我们传不是一个对象.如果想跟新视图。
应该使用ref函数

vue3函数setUp和reactive函数详细讲解

6 reactive传入数组 <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>

vue3函数setUp和reactive函数详细讲解

5 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>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwyjyy.html