【Vue3】setup语法糖下一些常见内容

不定期更新setup语法糖下常见的一些内容如watch、computed等】

零、vue3 setup语法糖基本用法

<template>
  <div></div>
</template>

<script lang='ts' setup>
import { defineComponent,defineEmits,ref,reactive,computed,watch, } from 'vue';
let props = defineProps({
  vModel: { type: [String, Number] },
});
</script>

<style lang='scss' scoped>
</style>

Tips:
(1)使用setup语法糖后不需要return

一、watch的用法


//监听单个对象
watch(
	() => props.vModel,
	(newVal: any, oldVal: any) => {
		if (newVal && newVal !== oldVal) {
			//do sth
		}
	},
	{ immediate: true, deep: true }
);

//监听多个对象
watch(
	[() => props.vModel1, () => props.vModel2],
	([newVal1, newVal2],[oldVal1, oldVal2]) => {
		//do sth
	},
	{ immediate: true, deep: true }
);

Tips:
(1)第一个参数是监听的对象,第二个参数是监听对象的新旧值,第三个参数是配置,immediate表示默认执行一次,deep表示深度监听
(2)监听多个数据时,每一项数据发生变化,都会进入监听,因此需要根据实际需求判断是多数据一起监听还是分别监听

二、computed的用法

//基础用法
let modelData = computed(() => {});

//get set
let modelData = computed({
	get() {
		return props.vModel;
	},
	set(newVal: any) {
		//do sth
	}
});

//mapActions
const func = computed(() => ({ ...mapActions(['func']) })).value.func.bind({ $store: store });

//mapState
const stations = computed(() => ({ ...mapState(['stations']) })).value.stations.bind({ $store: store });

//mapGetters, mapMutations使用方式类似


三、emit用法

const emit = defineEmits(['func1','func2']);
function menuChecked() {
	let params: any = []
	emit('func1', params);
	emit('func2', params);
}

Tips:
(1)emit的方法需要预先定义,为String数组
(2)父组件内不要忘记在子组件上加上@func1="function"的声明

四、引入store

import { useStore } from 'vuex';
const store = useStore();

//引入数据
let district = store.state.district;
//调用actions内方法
store.dispatch('func');

五、引入router

import { useRouter } from 'vue-router';
const router = useRouter();
router.push(`/`);

import router from '@/router';
router.push(`/`);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值