Reputation: 1401
I am migrating my vue 2 application to vue 3. I read the computed property in vue 3 with composition api.
Here is the vue 2 computed property to provide some common data to different component. My question is how to migrate it vue 3 computed property using composition api with getters and setters.
sharingDataInComponents() {
let obj={}, objProperty = Object.defineProperty;
// variable
objProperty(obj, 'size' , {get:()=>this.size});
objProperty(obj, 'shape' , {get:()=>this.shape});
objProperty(obj, 'navigation' , {get:()=>this.navigation});
objProperty(obj, 'addBtn' , {get:()=>this.addBtn});
// function
objProperty(obj, 'onAddClick', {get:()=>this.onAddClick});
return obj;
},
How to migrate this? I am new to vue 3 composition api.
Upvotes: 2
Views: 1828
Reputation: 23490
Try like in following snippet:
const { ref, computed } = Vue
const app = Vue.createApp({
setup() {
const size = ref(35)
const shape = ref('cirlcle')
const navigation = ref('left')
const addBtn = ref(true)
const onAddClick = () => {console.log('add')}
const sharingDataInComponents = computed(() => {
let obj={}, objProperty = Object.defineProperty;
// variable
objProperty(obj, 'size' , {get:()=>size.value});
objProperty(obj, 'shape' , {get:()=>shape.value});
objProperty(obj, 'navigation' , {get:()=>navigation.value});
objProperty(obj, 'addBtn' , {get:()=>addBtn.value});
// function
objProperty(obj, 'onAddClick', {get:()=>onAddClick});
return obj;
})
return { size, shape, navigation, addBtn, onAddClick, sharingDataInComponents }
}
})
app.mount('#demo')
<script src="https://unpkg.com/[email protected]/dist/vue.global.prod.js"></script>
<div id="demo">
<div @click="sharingDataInComponents.onAddClick">
{{ sharingDataInComponents.size }}
</div>
</div>
Upvotes: 1