setup基础用法
setup是vue3新增的一个属性,默认写法是在代码中用setup方法,然后在setup中return。
setup(){
const func = () => {
//这里写方法里的内容
}
return func
}
用setup语法糖则无需这么繁琐,并且不需要使用this,切记。
<script setup>
//直接写方法,在dom中直接调用即可
const editFunc = () => {}
</script>
<template>
<div @click="editDrawer">编辑按钮</div>
</template>
setup中使用watch,props,emit
props用defineProps代替。
emit用defineEmits代替。
watch监听props,值以函数返回值的形式传入。
<script setup>
const props = defineProps({
rightMenuStyle: String,
rightMenu: String
})
const emit = defineEmits(['editDrawer'])
watch(()=>props.rightMenuStyle, (newVal, oldVal)=>{
if(val){
state.styleObj = JSON.parse(newVal)
}
}, {deep: true, immediate: true})
const editDrawer = (val) => {
emit('editDrawer', val.type)
}
</script>
<template>
<div @click="editDrawer">编辑按钮</div>
</template>
watch监听多个值
watch([()=>props.rightMenuStyle, ()=>props.rightMenu], (newVal, oldVal)=>{
// 请注意,监听多个值,有一个值变化,watch就会执行,所以为了不频繁触发,不建议同时监听多个值
}, {deep: true, immediate: true})
| 本文章会一直更新,请持续关注哦,一起学习!