Vue3_基础

270 阅读1分钟
  • .babel文件:将es6转成es5

  • setup()函数中的this是undefined,第七节11:52秒

  • ref定义的对象可以直接被赋值

    <script lang="ts" setup>
    import { reactive,ref, watch } from 'vue';
    
    let animal = ref({
        'name':'穷鬼',
        'age':25
    })
    
    function changeName(){
        animal.value.name += '~'
    }
    
    function changeAge(){
        animal.value.age +=1
    }
    
    // 重新赋值
    function changeAll(){
        animal.value = {'name':'大穷鬼', 'age':66}
    }
    </script>
    
  • reactive定义的对象需要用Object.assign()函数重新赋值

    <script lang="ts" setup>
    import { reactive } from 'vue';
    
    let car = reactive({
        'name': '秦Plus ev',
        'age': 2
    })
    
    function changeName(){
        car.name += '~'
    }
    function changeAge(){
        car.age += 1
    }
    
    function changeAll(){
        car = Object.assign(car, {'name':'大穷鬼', 'age':666})
    }
    </script>
    
  • watch函数的返回值是一个函数,调用后停止监视

    let height = ref(1)
    
    function changeHeight() {
        height.value += 1
    }
    
    let stopWatch = watch(height, (newValue, oldValue)=>{
        console.log(stopWatch)
        if(height.value >5){
            stopWatch()
        }
    })
    
  • watch函数监视 reactive对象时默认就是深度监听,监视ref对象时 需要增加参数deep:true才可以深度监听对象变化

    let animal = ref({
        name: 'ccb',
        age: 24
    })
    function changeAge() {
        animal.value.age += 1
    }
    watch(animal, (newValue, oldValue) => {
        console.log('年龄变化了', newValue, oldValue)
    }, {deep:true})
    
  • toRefs()能把reactive()创建的对象解构出来后的属性 依然保持响应式

    import { reactive, toRefs } from 'vue';
    
    export default {
      setup() {
        const state = reactive({
          count: 0,
          name: 'Vue 3'
        });
    
        // 正确做法:使用 toRefs 保持响应式
        const { count, name } = toRefs(state);
    
        // 这样 count 和 name 保持响应式特性
        return {
          count,
          name
        };
      }
    }