Vue3.0初体验
最近看了Vue3.0的相关信息,相比Vue2.0有以下优点:
Performance:性能更比Vue 2.0强。Tree shaking support:可以将无用模块“剪辑”,仅打包需要的。Composition API:组合APIFragment, Teleport, Suspense:“碎片”,Teleport即Protal传送门,“悬念”Better TypeScript support:更优秀的Ts支持Custom Renderer API:暴露了自定义渲染API
项目搭建:
由于现在还只是插件形式,所有要先创建Vue2.0项目再进行安装插件,插件如下:
建好Vue2.0项目后,进入文件夹运行此命令 vue add vue-next ,完后Vue3.0创建完毕。
代码:
所需模块的导入,与Vue2.0最大区别就是需要啥导入啥,不用全部一起导入





其次就是所有逻辑都在setup函数中编写,其相当于Vue2.0的BeforeCreate、created钩子,
声明周期:
onBeforeMount
onMounted
onBeforeUpdate
onUpdated
onBeforeUnmount
onUnmounted
响应式原理:Vue3.0用Proxy代替Vue2.0的defineProperty,所以更快
const dproxy = new Proxy(obj, {
get: function(target, key, receiver) {
console.log(receiver);
return target[key];
},
set: function(target, key, newVal, receiver) {
console.log(receiver);
target[key] = newVal;
return target[key];
}
});
dproxy.name = 'terry';
console.log(obj.name);
重写Vdom加静态标记,优化diff算法,所以更快
自定义响应式数据:
const useDebouncdedRef = (value, delay = 200) => {
let timeout;
return customRef((track, trigger) => {
return {
get() {
track();
return value;
},
set(newValue) {
clearTimeout(timeout);
timeout = setTimeout(() => {
value = newValue;
trigger();
}, delay);
}
};
});
};
原生响应式:两种方式
const count = ref(0);
const state = reactive({
msg: 'wellcome to Vue3.0!',
size: 0
});
改变值用count.value方式,如
const increament = () => {
count.value++;
};
watch监听:两种方式
watch([() => count.value, () => customText.value], val1 => {
console.log(val1);
// console.log(`count is ${val1}`);
// console.log(`customText is ${val1}`);
});
watchEffect(() => {
console.log(`i am watchEffect:${count.value}`);
console.log(`i am watchEffect:${customText.value}`);
});
计算属性computed:
const doubleCount = computed(() => count.value * 2);
获取上文对象:
const { ctx } = getCurrentInstance();
console.log(ctx);
ctx.$store.commit('setTestA', count)
store与router
const store = useStore();
const router = useRouter();
父子或父与孙子组件传值provide与inject
provide('injdectmsg', 'i am a provide');
const injectMsg = inject('injdectmsg')
以上就是Vue3.0的知识,欢迎大家一起学习交流! (Vue3.0开发仿小米商城github地址:https://github.com/ytg123/Vue3.0-Shopping)
浙公网安备 33010602011771号