快速学习使用 vue3 干货满满
本文为 vue2
用户,想学习 vue3
看的文章,教你快速的适应vue3
的语法,保证看完本文你直接可以做项目,主要讲解vue3中新增的语法,不包括 v-if ,v-show, v-on
在 vue2
中已经存在的api,以及包括KeepAlive
这一类组合api。
如需学习,可以跳转到 VUE3
VUE3 学习
- 在vue3中新增了setup这个语法糖
setup
可以理解为模板中的表达式和 <script setup> 中的代码处在同一个作用域中
下面所有的讲解都是基于setup
语法糖中,在使用vue的api的时候,需要按需导入,才可使用
// helloWorld.vue
<template>
</template>
<script setup>
// 使用语法糖
</script>
- 响应式的状态
reactive 和 ref
// VUE2
export default {
data() {
return {
msg: "",
map: {name:"",age:""}
}
}
}
// VUE3
/*
reactive 和 ref
相同点:都可以创建响应式的数据
不同点:reactive是不支持创建基本类型响应式数据的
ref 支持基本类型的 string, number, boolean,
ref在设置值的使用 必须使用 .value
*/
<script setup>
import { reactive,ref } from 'vue';
import { $ref } from 'vue/macros'; // 语法糖
const author = reactive({
name: 'jo',
books: [
"vue111",
"vue222"
]
});
const state = reactive({count: 0});
const age = $ref(18);
console.log(age); // 不需要使用 .value 也可以设置值
const count = ref(0);
console.log(count .value);
// 配合使用
const map = reactive(new Map([['count',ref(0)]]));
console.log(map.get('count').value);
</script>
- 计算属性
computed
<template>
<p>{{ publish }}</p>
</template>
<script setup>
import { computed } from 'vue';
// 计算属性
const publish = computed(() => {
return 'yes'
});
</script>
- 监听
watch 和 watchEffect
<script setup>
import { watch, watchEffect } from 'vue';
const question = ref(0);
// 监听一个ref
watch(question, async (newQuestion, oldQuestion) => {
console.log(newQuestion,oldQuestion)
});
const x = ref(0);
const y = ref(0);
watch(
() => x.value + y.value,
(sum) => {
console.log(sum);
},
{deep: true} // 强制转成深层监听
);
// watch 懒执行,只有在数据源变化的时候,才执行
watchEffect(async () => {
},{
flush: 'post' // 侦听器回调中能访问被 Vue 更新之后的DOM ,也可以使用 watchPostEffect 函数
});
</script>
- 组件完成初始渲染并创建 DOM 节点后 生命周期
<script setup>
import { onMounted } from 'vue';
onMounted(() => {
});
</script>
- 父子组件传值以及包括 依赖注入
defineProps, defineEmits, provide, inject
使用setup语法糖,将 子组件导入 直接会注册,不用像 VUE2 中需要手动注册
// VUE2 语法
import Child from './Child.vue';
components: {
Child
}
// VUE3
// helloworld.vue
<template>
<!--父子传值,函数调用-->
<Child title="22222" age="18" @childText="childText" >
<!--插槽-->
999999999999999
</Child>
</template>
<script setup>
// 自动注册组件
import Child from './Child.vue';
import { provide } from 'vue';
// 注入名, 值 ||| 为组件后代提供数据
// provide('message','hello');
const location = ref("north pole");
function updatelocation() {
location.value = "22222";
}
// 子组件传递的值
function childText(e) {
console.log(e)
}
// 可以转递一个对象的形式, 也可以设置注入方不可以修改数组 ,可以使用 readonly
// provide搭配 inject 使用, 子组件或更深的组件 使用 inject 即可获取值,无需一层一层的传值
provide('location',
// readonly({location,updatelocation})
{ location,updatelocation }
);
</script>
// Child.vue
<template>
<p>
{{props.title}}
<button @click="childFn">子组件</button>
<slot />
</p>
</template>
<script setup>
import {
defineProps
,defineEmits
,defineComponent
,inject
} from 'vue';
// 注入即可使用 父组件或更高组件传递的值 provide搭配inject 使用
const {location,updatelocation} = inject('location');
// 接受父组件传递的值,约束接收 'title','age'
const props = defineProps(['title','age']);
const emit = defineEmits(['childText']);
function childFn() {
emit('childText','22222'); // 参数2 为传递的值
}
defineComponent({
name: "ChildHe"
})
</script>
- 在DOM渲染之后被触发,以获取最新的DOM节点
nextTick
// VUE2 语法
this.$nextTick(() => { })
// VUE3 语法
import { nextTick } from 'vue';
nextTick(() => { })
vuex
的使用
在vue3 中vuex
不再推荐使用,替换 vuex
的是 pinia
-
- 下载并且在main文件中注册
yarn add pinia
npm install pinia --save
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
createApp(App).use(createPinia()).mount('#app');
-
- 在 vue 中使用
// auth-store.js
import { defineStore } from 'pinia';
export const useAuthStore = defineStore('auth', {
state: () => ({countPinia: 1}),
getters: {
},
actions: {
increment() {
return this.countPinia;
}
}
});
// index.js
import { defineStore } from 'pinia';
import { useAuthStore } from './auth-store.js';
export const useStore = defineStore('main', {
state: () => ({countPinia: 1}),
getters: {
double() {
return this.countPinia * 2;
}
},
actions: {
increment() {
// 使用auth-store 的 store
const auth = useAuthStore();
console.log(auth);
console.log(this.countPinia);
return this.countPinia;
}
}
});
// helloworld.vue
<template>
</template>
<script setup>
import {useStore} from "index.js";
const storePinia = useStore();
storePinia.countPinia++;
storePinia.increment();
console.log(storePinia.double)
console.log(storePinia.countPinia + "-------------------")
</script>
VUE3 中使用 TS 语法
<script setup lang="ts">
import {
ref,
defineProps,
defineEmits,
Ref,
reactive,
computed,
provide,
inject,
InjectionKey
} from 'vue';
// const props = defineProps(['foo','bar'=100]);
interface Props {};
const { foo, bar = 100 } = defineProps<Props>();
// const emit = defineEmits(['change','update']);
const emit = defineEmits<{
(e:"change", id: number): void,
(e:"update", value: string): void,
}>();
// const year = ref('2000');
const year : Ref<string | number> = ref('2000');
// const book = reactive({title: "2222"});
interface Book {
title: string,
year?: number
}
const book:Book = reactive({title: "2222"});
// const double = computed(() => {return 0});
const double = computed<Number>(() => {
return 0
});
// function handle(event){console.log(event)};
function handle(event: Event) {
console.log((event.target as HTMLInputElement).value);
}
// const key = "name";
const key = Symbol as InjectionKey<string>
provide(key,"fpp");
const foo = inject(key);
</script>
白嫖完记得学习下 vue3 响应式系统的原理
最后附上 demo代码
祝大家学习愉快,工作顺利