【不定期更新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(`/`);