Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Chron's avatar
Level 6

Conditional declarations

Is it possible to wrap declarations in script setup with if and else? Here's an example

<script setup>
import { ref, onMounted } from 'vue'

const props = defineProps({
  foo: {
    type: Boolean,
    default: false
  }
});

if (props.foo) {
  const bar = ref(null);

  onMounted(() => {
      // do something...
  });
}
</script>
0 likes
5 replies
vincent15000's avatar

I don't think that it's a good idea.

Put the condition inside the onMounted() function and declare the bar property outide the onMounted() function and keep it null if the condition is false.

martinbean's avatar

@chron Why don’t you describe the actual problem or use case? Then someone may be able to suggest a more appropriate solution. No one can say if this is a good or not based on foos and bars.

1 like
Chron's avatar
Level 6

@martinbean

I have a default layout and different one specifically for the home page.

Default layout has a non-collapsible sidebar while other has one.

I'm planning to use the same layout file for both home and other pages.

This is the layout

BaseLayout[collapsible="true|false"]
   |   Header
   |   Sidebar
   |   Content
BaseLayout

Header uses IntersectionObserver API. Sidebar uses Offcanvas from Bootstrap.

Header and Sidebar depends on the layout prop collapsible. If the prop is false, Header doesn't use IO and Sidebar doesn't use Offcanvas.

Would it be better if I could just separate the layout for both home and other pages? That could mean, I also have a different Header and Sidebar. That way, they wouldn't need the collapsible prop anymore.

I'm also using Inertia, if that helps.

I hope it's clear.

1 like
MaverickChan's avatar

yes you can , use watch.

watch(() => props.foo, (newValue) => {
       //do something you want
    },{
        immediate: true
    })
1 like

Please or to participate in this conversation.