Vue3学习笔记.md
创建Vue3项目
使用 vue-cli 创建
vue-cli的版本一定要在4.5.0以上
// 安装或者升级
npm install -g @vue/cli
//查看版本 保证 vue cli 版本在 4.5.0 以上
vue --version
// 创建项目
vue create my-project
//然后根据提示一步一步傻瓜式操作就行了
使用 Vite 创建
// 初始化viete项目
npm init vite-app <project-name>
// 进入项目文件夹
cd <project-name>
// 安装依赖
npm install
//启动项目
npm run dev
若选择ts
main.ts
// 引入createApp函数,创建对应的应用,产生应用的实例对象
import { createApp } from 'vue';
// 引入app组件(所有组件的父级组件)
import App from './App.vue';
// 创建app应用返回对应的实例对象,调用mount方法进行挂载 挂载到#app节点上去
createApp(App).mount('#app');
根组件app.vue
/Vue2组件中的html模板中必须要有一对根标签,Vue3组件的html模板中可以没有根标签
<template>
<img alt="Vue logo" src="./assets/logo.png">
<!-- 使用子级组件 -->
<HelloWorld msg="Welcome to Your Vue.js + TypeScript App" />
</template>
<script lang="ts">
// 这里可以书写TS代码
// defineComponent函数,目的是定义一个组件 内部可以传入一个配置对象
import { defineComponent } from 'vue';
//引入子级组件
import HelloWorld from './components/HelloWorld.vue';
// 暴露出去一个定义好的组件
export default defineComponent({
// 当前组件的名字
name: 'App',
// 注册组件
components: {
// 注册一个子级组件
HelloWorld,
},
});
</script>
Composition API
Vue3的招牌特性,Composition API。
Composition API可以更方便的抽取共通逻辑。
Vue3兼容大部分Vue2语法,所以在Vue3中书写Vue2语法是没有问题的(废除的除外)。
setup
setup是组合Composition API中的入口函数,也是第一个要使用的函数。
setup只在初始化时执行一次,所有的Composition API函数都在此使用。
可以通过console.log看到setup是在beforeCreate生命周期之前执行的(只执行一次)
beforeCreate() {
console.log('beforeCreate执行了');
},
setup() {
console.log('setup执行了');
return {};
},
//setup执行了
//beforeCreate执行了
由此可以推断出setup
执行的时候,组件对象还没有创建,组件实例对象this
还不可用,此时this
是undefined
, 不能通过this
来访问data/computed/methods/props
。
返回对象中的属性会与data
函数返回对象的属性合并成为组件对象的属性,返回对象中的方法会与methods中的方法合并成功组件对象的方法,如果有重名, setup
优先。因为在setup
中this
不可用,methods
中可以访问setup
提供的属性和方法, 但在setup
方法中不能访问data
和methods
里的内容,所以还是不建议混合使用。
setup函数如果返回对象, 对象中的 属性 或 方法 , 模板 中可以直接使用
//templete
<div>{{number}}</div>
//JS
setup() {
const number = 18;
return {
number,
};
},
setup不能是一个async函数: 因为返回值不再是return的对象, 而是promise, 模板中就不可以使用return中返回对象的数据了。
setup的参数(props,context)
props: 是一个对象,里面有父级组件向子级组件传递的数据,并且是在子级组件中使用props接收到的所有的属性
context:上下文对象,可以通过es6语法解构 setup(props, {attrs, slots, emit})
- attrs: 获取当前组件标签上所有没有通过props接收的属性的对象, 相当于this.$attrs
- slots: 包含所有传入的插槽内容的对象, 相当于 this.$slots
- emit: 用来分发自定义事件的函数, 相当于 this.$emit
演示attrs和props
//父组件
<template>
<child :msg="msg" msg2='哈哈哈' />
</template>
<script lang='ts'>
import { defineComponent, ref } from 'vue';
// 引入子组件
import Child from './components/Child.vue';
export default defineComponent({
name: 'App',
components: {
Child,
},
setup() {
const msg = ref('hello,vue3');
return {
msg,
};
},
});
</script>
//子组件
<template>
<h2>子组件</h2>
<h3>msg:{{ msg }}</h3>
</template>
<script lang='ts'>
import { defineComponent } from 'vue';
export default defineComponent({
name: 'Child',
props: ['msg'],
setup(props, {attrs, slots, emit}) {
console.log('props:', props);//msg: "hello,vue3"
console.log('attrs:', attrs);//msg2: "哈哈哈"
return {};
},
});
</script>
演示emit
//父组件
<template>
<child @show="show" />
</template>
<script lang='ts'>
setup() {
const show = () => {
console.log('name:', 'hzw');
};
return {
show,
};
},
</script>
//子组件
<template>
<button @click='emitFn'>事件分发</button>
</template>
<script lang='ts'>
import { defineComponent } from 'vue';
export default defineComponent({
name: 'Child',
setup(props, { emit }) {
const emitFn = () => {
emit('show');
};
return {
emitFn,
};
},
});
</script>
ref
定义一个响应式的数据(一般用来定义一个基本类型的响应式数据Undefined、Null、Boolean、Number和String)
语法
const xxx = ref(initValue):
注意:script中操作数据需要使用xxx.value的形式,而模板中不需要添加.value
用一个例子来演示:实现一个按钮,点击可以增加数字
<template>
<div>{{count}}</div>
<button @click='updateCount'>增加</button>
</template>
在Vue2中
data() {
return {
conunt: 0,
};
},
methods: {
updateCount() {
this.conunt++;
},
},
在Vue3中
setup() {
// ref用于定义一个响应式的数据,返回的是一个Ref对象,对象中有一个value属性
//如果需要对数据进行操作,需要使用该Ref对象的value属性
const count = ref(0);
function updateCount() {
count.value++;
}
return {
count,
updateCount,
};
},
在Vue2中我们通过this.$refs来获取dom节点,Vue3中我们通过ref来获取节点
首先需要在标签上添加ref='xxx',然后再setup中定义一个初始值为null的ref类型,名字要和标签的ref属性一致
const xxx = ref(null)
注意:一定要在setup的return中返回,不然会报错。
还是用一个例子来演示:让输入框自动获取焦点
template>
<h2>App</h2>
<input type="text">---
<input type="text" ref="inputRef">
</template>
<script lang="ts">
import { onMounted, ref } from 'vue'
/*
ref获取元素: 利用ref函数获取组件中的标签元素
功能需求: 让输入框自动获取焦点
*/
export default {
setup() {
const inputRef = ref<HTMLElement|null>(null)
onMounted(() => {
inputRef.value && inputRef.value.focus()
})
return {
inputRef
}
},
}
</script>
reactive
语法
const proxy = reactive(obj)
作用
定义多个数据的响应式,接收一个普通对象然后返回该普通对象的响应式代理器对象(Proxy),响应式转换是"深层的":会影响对象内部所有嵌套的属性,所有的数据都是响应式的。
<template>
<h3>姓名:{{user.name}}</h3>
<h3>年龄:{{user.age}}</h3>
<h3>wife:{{user.wife}}</h3>
<button @click="updateUser">更新</button>
</template>
setup() {
const user = reactive({
name: 'tt',
age: 18,
wife: {
name: 'xioaohong',
age: 18,
books: ['红宝书', '设计模式', '算法与数据结构'],
},
});
const updateUser = () => {
user.name = '小红';
user.age += 2;
user.wife.books[0] = '金瓶梅';
};
return {
user,
updateUser,
};
},
computed函数
与Vue2中的computed配置功能一致,返回的是一个ref类型的对象
计算属性的函数中如果只传入一个回调函数 表示的是get操作
import { computed } from 'vue';
const user = reactive({
firstName: '韩',
lastName: '志伟',
});
const fullName1 = computed(() => {
return user.firstName + user.lastName;
});
return {
user,
fullName1,
};
计算属性的函数中可以传入一个对象,可以包含set和get函数,进行读取和修改的操作
const fullName2 = computed({
get() {
return user.firstName + '_' + user.lastName;
},
set(val: string) {
const names = val.split('_');
user.firstName = names[0];
user.lastName = names[1];
},
});
return {
user,
fullName2,
};
watch函数
与Vue2中的watch配置功能一致,
- 参数1:要监听的数据
- 参数2:回调函数
- 参数3:配置
作用
监视指定的一个或多个响应式数据, 一旦数据变化, 就自动执行监视回调
默认初始时不执行回调, 但可以通过配置immediate为true, 来指定初始时立即执行第一次
通过配置deep为true, 来指定深度监视
import { watch, ref } from 'vue';
const user = reactive({
firstName: '韩',
lastName: '志伟',
});
const fullName3 = ref('');
watch(
user,
({ firstName, lastName }) => {
fullName3.value = firstName + '_' + lastName;
},
{ immediate: true, deep: true }
);
return {
user,
fullName3,
};
watch监听多个数据,使用数组
watch监听非响应式数据的时候需要使用回调函数的形
watch([()=>user.firstName,()=>user.lastName,fullName3],()=>{console.log('我执行了')})
watchEffect函数
作用
监视数据发生变化时执行回调,不用直接指定要监视的数据, 回调函数中使用的哪些响应式数据就监视哪些响应式数据,默认初始时就会执行第一次, 从而可以收集需要监视的数据。
import { watchEffect, ref } from 'vue';
const user = reactive({
firstName: '韩',
lastName: '志伟',
});
const fullName4 = ref('');
watchEffect(() => {
fullName4.value = user.firstName + '_' + user.lastName;
});
return {
user,
fullName4,
};
watchEffect可以实现计算属性set方法
watchEffect(() => {
const names = fullName3.value.split('_');
user.firstName = names[0];
user.lastName = names[1];
});
toRefs
作用
把一个响应式对象转换成普通对象,该普通对象的每个属性都是一个 ref
应用
我们使用reactive创建的对象,如果想在模板中使用,就必须得使用xxx.xxx的形式,如果大量用到的话还是很麻烦的,但是使用es6解构以后,会失去响应式,那么toRefs的作用就体现在这,,利用toRefs可以将一个响应式 reactive 对象的所有原始属性转换为响应式的ref属性。
<template>
<div>
name:{{name}}
</div>
</template>
<script lang='ts'>
import { defineComponent, reactive, toRefs } from 'vue';
export default defineComponent({
name: '',
setup() {
const state = reactive({
name: 'tt',
});
const state2 = toRefs(state);
setInterval(() => {
state.name += '===';
}, 1000);
return {
//通过toRefs返回的对象,解构出来的属性也是响应式的
...state2,
};
},
});
</script>
provide 与 inject
作用
实现跨层级组件(祖孙)间通信
代码演示
父组件
<template>
<h1>父组件</h1>
<p>当前颜色: {{color}}</p>
<button @click="color='red'">红</button>
<button @click="color='yellow'">黄</button>
<button @click="color='blue'">蓝</button>
<hr>
<Son />
</template>
<script lang="ts">
import { provide, ref } from 'vue'
import Son from './Son.vue'
export default {
name: 'ProvideInject',
components: {
Son
},
setup() {
const color = ref('red')
provide('color', color)
return {
color
}
}
}
</script>
子组件
<template>
<div>
<h2>子组件</h2>
<hr>
<GrandSon />
</div>
</template>
<script lang="ts">
import GrandSon from './GrandSon.vue'
export default {
components: {
GrandSon
},
}
</script>
孙子组件
<template>
<h3 :style="{color}">孙子组件: {{color}}</h3>
</template>
<script lang="ts">
import { inject } from 'vue'
export default {
setup() {
const color = inject('color')
return {
color
}
}
}
</script>
Vue3的特性
Teleport
作用
Teleport 提供了一种干净的方法, 让组件的html在父组件界面外的特定标签(很可能是body)下插入显示 换句话说就是可以把 子组件 或者 dom节点 插入到任何你想插入到的地方去。
语法
使用to属性 引号内使用选择器
<teleport to="body">
</teleport>
演示
//父组件
<template>
<div class="father">
<h2>App</h2>
<modal-button></modal-button>
</div>
</template>
<script lang="ts">
import ModalButton from './components/ModalButton.vue'
export default {
setup() {
return {}
},
components: {
ModalButton,
},
}
</script>
//子组件
<template>
<div class="son">
<button @click="modalOpen = true">
点我打开对话框
</button>
<teleport to="body">
<div v-if="modalOpen"
class="looklook">
看看我出现在了哪里
<button @click="modalOpen = false">
Close
</button>
</div>
</teleport>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
name: 'modal-button',
setup() {
const modalOpen = ref(false)
return {
modalOpen,
}
},
}
</script>
Suspense
作用
它们允许我们的应用程序在等待异步组件时渲染一些后备内容,可以让我们创建一个平滑的用户体验
语法
<Suspense>
<template v-slot:default>
<!-- 异步组件 -->
<AsyncComp />
</template>
<template v-slot:fallback>
<!-- 后备内容 -->
<h1>LOADING...</h1>
</template>
</Suspense>
vue3中引入异步组件的方式
const AsyncComp = defineAsyncComponent(() => import('./AsyncComp.vue'))
代码演示
父组件
<template>
<Suspense>
<!-- v-slot:defaul可以简写成#defaul -->
<template v-slot:default>
<AsyncComp/>
</template>
<template v-slot:fallback>
<h1>LOADING...</h1>
</template>
</Suspense>
</template>
<script lang="ts">
import { defineAsyncComponent } from 'vue'
const AsyncComp = defineAsyncComponent(() => import('./AsyncComp.vue'))
export default {
setup() {
return {
}
},
components: {
AsyncComp,
}
}
</script>
子组件
<template>
<h2>AsyncComp22</h2>
<p>{{msg}}</p>
</template>
<script lang="ts">
export default {
name: 'AsyncComp',
setup () {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
msg: 'abc'
})
}, 2000)
})
}
}
</script>
看到在异步组件加载出来之前,显示的是fallback中的内容
响应式数据的判断
作用
- isRef: 检查一个值是否为一个 ref 对象
- isReactive: 检查一个对象是否是由 reactive 创建的响应式代理
- isReadonly: 检查一个对象是否是由 readonly 创建的只读代理
- isProxy: 检查一个对象是否是由 reactive 或者 readonly 方法创建的代理
代码演示
setup() {
const state1 = ref(1);
console.log('isref:', isRef(state1));//isref: true
const state2 = reactive({});
console.log('isReactive:', isReactive(state2));//isReactive: true
const state3 = readonly({});
console.log('isReadonly:', isReadonly(state3));//isReadonly: true
const state4 = reactive({});
console.log('isProxy:', isProxy(state2));//isProxy: true
console.log('isProxy:', isProxy(state4));//isProxy: true
return {};
},
其他不常用特性
- shallowReactive
- shallowRef
- readonly
- shallowReadonly
- markRaw
- customRef
Emit派发事件可以对参数进行验证
父组件
<template>
<div>
<h2>我是父组件!</h2>
<Child @sonClick='sonClick' />
</div>
</template>
<script setup>
import Child from './components/Child.vue'
import { ref } from 'vue'
const sonClick = (value) => {
console.log(value)
}
</script>
子组件
<template>
<div>
我是子组件{{ msg }}
</div>
<button @click="handleClick(1)">我是按钮1</button>
<button @click="handleClick(2)">我是按钮2</button>
</template>
<script>
import { ref } from 'vue'
export default {
name: '',
emits: {
sonClick: (value) => {
if (value === 1) {
return true
} else {
return false
}
},
},
setup(props, { emit }) {
const msg = ref('hello')
const handleClick = (value) => {
emit('sonClick', value)
}
return {
msg,
handleClick,
}
},
}
</script>
我们分别点一下按钮1和按钮2,可以看到当我们点了按钮2的时候,控制台会发出警告,但是程序会继续执行