Vue3 Setup语法糖汇总

Vue3 Setup语法糖汇总

1.props定义

<script setup>
import { defineProps } from "vue"; // 部分高版本已主动注入 无需重复引入
const props = defineProps({
  foo: {
    type: String,
    default: '默认值',
  },
});
console.log(props.foo);// useage
</script>

2.组件Expose属性

<script setup>
import { ref,defineExpose } from "vue"; // defineExpose 部分高版本已主动注入

const testData = ref(null);
const refresh = () => {
  console.log("refresh");
}

defineExpose({
  testData,
  refresh
})
</script>

3.访问子组件成员

<template>
  <SonComponent ref="sonComponentRef"></SonComponent>
</template>

<script setup>
import SonComponent from './SonComponent';
import { onMounted, ref } from 'vue';
const sonComponentRef = ref(null);

onMounted(() => {
  sonComponentRef.value.refresh(); // 调用Son组件 refresh方法
  console.log(sonComponentRef.value.testData); // 访问Son组件 testData变量
});
</script>

4.组件Emit定义

<script setup>
import { onMounted } from 'vue';
const emit = defineEmits(['callFaterComponent']);
 // 父组件@callFaterComponent接受参数
onMounted(() => {
  emit('callFaterComponent', 'this is call father data');
});
</script>

5.自定义组件重写v-model

实现v-model双向绑定与change方法

<template>
  <div>
    <input :model-value="modelValue" :value="modelValue" type="text" @input="inputChange" />
  </div>
</template>

<script setup>
defineProps({
  modelValue: {
    type: String,
    default: '',
  },
});
const emit = defineEmits(['update:modelValue', 'change']);
const inputChange = (e) => {
  emit('update:modelValue', e.target.value);
  emit('change', e.target.value);
};
</script>

6. Setup支持async await快速调用

<script setup>
  import Api from '@/api/index.js'
  const data = await Api.getData()
  console.log(data)
</script>

7. watchEffect 副作用函数

类似computed,传入一个回调函数,将会被立即执行,同时建立参数依赖,当依赖参数发生值变化时,再次执行回调函数

<script setup>
import { ref, watchEffect } from 'vue';
const numA = ref(1);
const numB = ref(2);
const sum = ref(0);

watchEffect(() => {
  sum.value = numA.value + numB.value;
  console.log('this is sum::', sum.value);
});

setInterval(() => {
  numA.value += 1;
  numB.value += 2;
}, 1000);
</script>

当numA,numB的值发送变化时,将执行回调函数,即sum值得到更新。

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值