2019-08-12 14:03:22 3211浏览
今天千锋扣丁学堂HTML5培训老师给大家分享一篇关于Vue 3.0 前瞻Vue Function API新特性体验的详细介绍,首先最近Vue官方公布了Vue3.0最重要的RFC:Function-basedcomponentAPI,并发布了兼容Vue2.0版本的plugin:vue-function-api,可用于提前体验Vue3.0版本的Function-basedcomponentAPI。笔者出于学习的目的,提前在项目中尝试了vue-function-api。
import Vue from 'vue';
import { plugin as VueFunctionApiPlugin } from 'vue-function-api';
Vue.use(VueFunctionApiPlugin);
<template>
<div>
<span>count is {{ count }}</span>
<span>plusOne is {{ plusOne }}</span>
<button @click="increment">count++</button>
</div>
</template>
<script>
import Vue from 'vue';
import { value, computed, watch, onMounted } from 'vue-function-api';
export default {
setup(props, context) {
// reactive state
const count = value(0);
// computed state
const plusOne = computed(() => count.value + 1);
// method
const increment = () => {
count.value++;
};
// watch
watch(
() => count.value * 2,
val => {
console.log(`count * 2 is ${val}`);
}
);
// lifecycle
onMounted(() => {
console.log(`mounted`);
});
// expose bindings on render context
return {
count,
plusOne,
increment,
};
},
};
</script>
const MyComponent = {
props: {
name: String
},
setup(props, context) {
console.log(props.name);
// context.attrs
// context.slots
// context.refs
// context.emit
// context.parent
// context.root
}
}
value函数创建一个包装对象,它包含一个响应式属性value:
import { state, value } from 'vue-function-api';
const MyComponent = {
setup() {
const count = value(0);
const obj = state({
count,
});
console.log(obj.count) // 作为另一个响应式对象的属性,会被自动展开
obj.count++ // 作为另一个响应式对象的属性,会被自动展开
count.value++ // 直接获取响应式对象,必须使用.value
return {
count,
};
},
template: `<button @click="count++">{{ count }}</button>`,
};
import { value, computed } from 'vue-function-api';
const count = value(0);
const countPlusOne = computed(() => count.value + 1);
console.log(countPlusOne.value); // 1
count.value++;
console.log(countPlusOne.value); // 2
// 可写的计算属性值
const writableComputed = computed(
// read
() => count.value + 1,
// write
val => {
count.value = val - 1;
},
);
// double 是一个计算包装对象
const double = computed(() => count.value * 2);
watch(double, value => {
console.log('double the count is: ', value);
}); // -> double the count is: 0
count.value++; // -> double the count is: 2
const stop = watch(
[valueA, () => valueB.value],
([a, b], [prevA, prevB]) => {
console.log(`a is: ${a}`);
console.log(`b is: ${b}`);
}
);
stop();
import { onMounted, onUpdated, onUnmounted } from 'vue-function-api';
const MyComponent = {
setup() {
onMounted(() => {
console.log('mounted!');
});
onUpdated(() => {
console.log('updated!');
});
// destroyed 调整为 unmounted
onUnmounted(() => {
console.log('unmounted!');
});
},
};
setup() {
const state = reactive({
count: 0,
});
const double = computed(() => state.count * 2);
function increment() {
state.count++;
}
return {
...toBindings(state), // retains reactivity on mutations made to `state`
double,
increment,
};
}
【关注微信公众号获取更多学习资料】 【扫码进入HTML5前端开发VIP免费公开课】