'ref, computed alternatives in vue 2
I did a project in Vue 3 and I used ref and computed. Then I realized that I was supposed to do the project in Vue 2... and now I get : "export 'computed' was not found in 'vue'
"export 'ref' was not found in 'vue' ... I know that I need Vue 3 for those, that s why i want to ask if there are any alternatives:
this is where I use ref and computed:
import { ref, computed } from "vue";
export const collapsed = ref(false);
export const toggleSidebar = () => (collapsed.value = !collapsed.value);
export const SIDEBAR_WIDTH = 180;
export const SIDEBAR_WIDTH_COLLAPSED = 38;
export const sideBarWidth = computed(
() => `${collapsed.value ? SIDEBAR_WIDTH_COLLAPSED : SIDEBAR_WIDTH}px`
);
and here also:
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { collapsed } from './state'
export default {
props: {
to: { type: String, required: true },
icon: { type: String, required: true }
},
setup(props) {
const route = useRoute()
const isActive = computed(() => route.path === props.to)
return { isActive, collapsed }
}
}
</script>
<template>
<router-link :to="to" class="link" :class="{ active: isActive }" >
Solution 1:[1]
computed is also in vue 2, but in vue 2 you need to use options api :
export default {
data() {
return {
collapsed: false
}
},
computed: {
toggleSidebar() {
return this.collapsed.value = !this.collapsed.value
},
sideBarWidth() {
return `${this.collapsed ? SIDEBAR_WIDTH_COLLAPSED : SIDEBAR_WIDTH}px`
}
}
}
export default {
props: {
to: { type: String, required: true },
icon: { type: String, required: true }
},
computed: {
isActive() {
return this.$route.path === this.to
}
}
}
Solution 2:[2]
The Vue team has provided a stand-alone plugin for your scenario: @vue/composition-api.
It allows using Composition API in Vue2 projects.
All you have to do is install it and change the imports from vue to @vue/composition-api.
Not only you don't have to refactor everything from Composition API to Options API but, should the client decide to switch to Vue3 at some future point, all they need to do is change the imports back to vue and they're good to go.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
