Syntax of Vue 3 is changing inspired by React Hooks
export default {
setup() {
// reactive state
const state = reactive({
count: 0,
counterPowerOf2
})
// computed prop
const counterPowerOf2 = computed(() => Math.pow(state.count, 2))
function increment() {
state.count++
}
function decrement() {
state.count--
}
// expose to template
return {
increment,
decrement,
state
}
}
}
function useCounter(initialCounterState, power){
const count = ref(initialCounterState)
const counterPowerOf2 = computed(() => Math.pow(count.value, power))
function increment() {
count.value++
}
function decrement() {
count.value--
}
return {
count,
counterPowerOf2,
increment,
decrement
}
}
export default {
setup() {
const { state, increment, decrement, counterPowerOf2 } = useCounter(0, 2);
return {
state,
increment,
counterPowerOf2,
decrement
};
}
}
new Vue({
beforeCreate () {
},
setup () {
},
created () {
}
})
export default {
setup() {
const { count, increment, decrement, counterPowerOf2 } = useCounter(0, 2);
return {
count,
increment,
counterPowerOf2,
decrement
};
},
mounted(){
this.count = 40;
this.increment()
}
}
export default {
setup() {
const state = reactive({
count: 0
})
return {
state
}
}
}
reactive(obj) will return a new object that looks exactly the same as obj, but any mutation to the new object will be tracked.
It's implemented with Proxies so now we can add new properties to it instead of Vue.set like previously
reactive obj that has .value property and is fully reactive. Way better to use than reactive
reactive obj that has .value property and is fully reactive. Way better to use than reactive
creates a computed value
const { count, increment, decrement, counterPowerOf2 } = useCounter(0, 2);
onMounted(() => {
count.value = 40;
increment()
})
watching the reactive value
const searchInput = ref("")
const results = ref(0);
watch(() => {
results.value = eventApi.getEventCount(searchInput.value);
});
Install it as a plugin to Vue 2
yarn add @vue/composition-api
import Vue from 'vue';
import VueCompositionApi from '@vue/composition-api';
Vue.use(VueCompositionApi);
Can be used outside of components
Code organization
Logic reuse
Tree shaking for non major Vue projects
Improved TS support
Composition
flexible
performance
Code organization
@VladimirNovick