vue3 基础(一)

98 阅读1分钟

响应式变量几种写法

1、 setup + ref 定义

    const data = ref('linda');
    const changeData = ()=>{
        data.value = 'linda2'
    }
    return {
        data,
        changeData-
    }
  }

2、setup + reactive + toRefs

    const data = reactive({
        name: 'linda',
        changeData:()=>{
            data.name = 'linda2'
        }
    });
    return {
        ...toRefs(data)
    }
  }

defineProps

  • 写在<script setup> 中,不需要导入
<script setup>
  // 无需导入直接使用
  type Props = {
    name: string;
    age: number | string;
  };
  const props = defineProps<Props>({
    name: String,
  });
</script>
或者
const props = defineProps(['name', 'age']) as Props
或者默认值
  const props = withDefaults(defineProps<Props>(), {
      name: 'linda'
  });
  • 支持类型、是否必填、校验、默认值
  const props = defineProps({
    name: {
      type: String,
      require: true,
      default: 'linda',
      validator: (value) => {
        return value.lengt
        h > 1;
      },
    },
  });
  • 声明多类型
defineProps({
  name: [string, Number]
})
  • PropType
import type { PropType } from 'vue'
//用于在用运行时 props 声明时给一个 prop 标注更复杂的类型定义。
 props: { 
    person: { 
        type: Object as PropType<Person>, 
        required: true 
   } 
 }
  • 传递给defineProps的泛型参数本身不能是一个导入的类型

watch

  • watch 监听多个值
watch(
    [() => state1.count, state2.value], ([newVal1, newVal2], [oldVal1, oldVal2]) => {
        console.log('watch监听中的newVal:', newVal1, newVal2);
        console.log('watch监听oldVal:', oldVal1, oldVal2);
    }
)

1、watch函数的第一个参数为ref基本类型时不需要添加.value, 如果ref 是对象,修改的是ref定义的对象中的属性,newValue和oldValue都是新值,因为他们是同一个对象,除非修改整个ref定义的对象

2、watch可以监听多个数据,使用数组封装

3、监听对象时,不开启deep,直接修改嵌套属性不会触发回调

4、监听对象具体属性,不用开启deep,要第一个参数写成函数的写法,或者:

const getter = () => b.name
watch(getter, (newValue, oldValue) => {})