vue3越来越主流了,但是很多人还不习惯vue3的组合式API写法,依旧喜欢用选项是API,但是很多功能的写法是不同的,比如我今天要分享的store写法。
我用的store是pinia。
选项式API(script里不带setup)的写法:
在setup里将store实例化,然后其他地方用this调用即可,watch里不需要加this。
<script>
import useDesignerStore from '@/store/modules/designer';
export default {
name: 'cpt-button',
setup() {
const designerStore = useDesignerStore();
return {
designerStore
}
},
watch: {
'designerStore.refreshCptData': {
handler() {
this.designerStore.clearCurrentCpt()
}
}
},
created() {
this.designerStore.setRefreshCptData();
}
}
</script>
组合式API(script里带setup)的写法:
<script setup>
import useDesignerStore from '@/store/modules/designer';
const designerStore = useDesignerStore();
watch(
() => designerStore.refreshCptData,
() => {
designerStore.clearCurrentCpt()
}
)
const setRefreshCptData = ()=>{
designerStore.setRefreshCptData()
}