一、初识vue31.1、代码体验 vue2代码 export default { data(){ return { count:0 } }, methods:{ addCount(){ this.count++ } } } vue3代码 import {reactive, ref} from "vue"; import Child from "@/components/Child.vue"; const user=reactive({ name:'你好' }) const message='this is father conent'; const count = ref(0);
1.2、vue3优点 二、创建vue3项目2.1、执行命令 npm init vue@latest npm下载慢,尝试使用pnpm安装依赖包 2.2、根据提示安装依赖 三、组合式API3.1、在setup函数中写的数据和方法,必须在末尾以对象的方式return,页面才能接受 <script> export default { setup(){ const message = 'this is message' const logMessage = ()=>{ console.log(message) } // 必须return才可以 return { message, logMessage } } } </script> 3.2、<script setup>语法糖 script标签添加setup标记,不需要再写导出语句,默认会导出。 <template> <main> {{message}} </main> </template> <script setup lang="ts"> const message='this is father conent'; </script> 注意:setup中使用this,返回undefined,在beforeCreate钩子之前自动执行。 四、ref、reactice函数4.1、ref 接收简单类型或者对象数据,并返回一个响应式的对象。 <script setup> // 导入 import { ref } from 'vue' // 执行函数 传入参数 变量接收 const count = ref(0) const setCount = ()=>{ // 修改数据更新视图必须加上.value count.value++ } </script> <template> <button @click="setCount">{{count}}</button> </template> 4.2、reactive对比ref 相同:都是用来声明响应式数据 不同:
建议:使用ref数据,减少记忆负担 五、computed计算属性思想跟vue2一致,只是修改了api写法。使用前导入computed函数 import {computed, ref} from "vue"; const count = ref(0); const doubleCount = computed(()=>count.value * 2) 注意:计算属性不应该出现的场景 1、异步操作。比如修改、新增请求; 2、属性值应该是只读的,不能修改属性值; 六、watch函数watch函数用来监听数据状态变化。 6.1、单个数据 import {ref, watch} from "vue"; const count = ref(0); watch(count,(newValue,oldValue)=>{ console.info('count值改变',newValue,oldValue); }); 6.2、多个数据 import {ref, watch} from "vue"; const count = ref(0); const message ='hello world'; // 监听多个数据 watch([count,message], ([newValue,newMessage],[oldValue,oldMessage])=>{ console.info('count,message改变',newValue,newMessage,oldValue,oldMessage); }) 6.3、对象属性 import {ref, watch} from "vue"; const user=reactive({ name:'你好' }) watch(()=>user.name,()=>{ console.info('user.name改变',user.name); }) 6.4、整个对象(复杂) watch监听的ref对象默认是浅层侦听的,直接修改嵌套的对象属性不会触发回调执行,需要开启deep。 const user = reactive({ name: "tom", info: { gender: "男", age: 18, }, }); // 4. 监听响应式对象数据的一个数据,复杂类型 // watch(()=>数据, 改变后回调函数, {deep: true}) watch(user,() => { console.log("数据改变了"); }, { // 开启深度监听 deep: true, } ); 使用watch监听,配置默认执行
|
|