I am currently having this event in a vue3 component
:
<template>
<div class="hamburger-toggle" @click="toggle" :class="{ nav__open: isActive }">
</template>
<script>
export default {
name: "navbar",
data() {
return {
isActive: true
}
},
methods: {
toggle: function () {
this.isActive = !this.isActive;
}
}
}
</script>
How would I write this in the composition api
?
Failed attempt:
<script>
export default {
props: {
isActive: false
},
setup(props) {
function toggle(props) {
props.isActive = !props.isActive;
}
}
}
</script>
CodePudding user response:
Try like this (in composition API you use ref or reactive instead data function, and you return your functions/reactive data):
<template>
<div class="hamburger-toggle" @click="toggle" :class="{ nav__open: isActive }">
</template>
<script>
import { ref } from "@vue/reactivity";
export default {
name: "navbar",
setup() {
const isActive = ref(true)
const toggle = () => {
isActive.value = !isActive.value
}
return { isActive, toggle }
}
</script>
CodePudding user response:
Also, it will work with a little less code:
<template>
<div @click="isActive = !isActive">
...
</div>
</template>
<script setup>
import { ref } from "vue";
const isActive = ref(true)
</script>
you can read here about the <script setup>