vite创建项目
1. 运行创建项目命令:
# 使用npm
npm create vite@latest
# 使用yarn
yarn create vite
# 使用pnpm
pnpm create vite
2 . 总结vue3写法的不同
平常组件
<template>
<div>节点1</div>
<div>节点2</div>
</template>
main.js
import { createApp } from 'vue'
import App from './App.vue'
// 根据App组件创建一个应用实例
const app = createApp(App)
// app应用挂载(管理)index.html的 #app 容器
app.mount('#app')
index.html
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
vue3 组合式api
1. setup函数
setup
函数是Vue3
特有的选项,作为组合式API的起点- 从组件生命周期看,它在
beforeCreate
之前执行 - 函数中
this
不是组件实例,是undefined
- 如果数据或者函数在模板中使用,需要在
setup
返回 - 今后在vue3的项目中几乎用不到
this
, 所有的东西通过函数获取。
2. reactivel函数
- 从
vue
中导出reactive
函数 - 在
setup
函数中,使用reactive
函数,传入一个普通对象,返回一个响应式数据对象 - 最后
setup
函数返回一个对象,包含该响应式对象即可,模板中可使用 reactive
函数通常定义:复杂类型的响应式数据- 不能转换简单数据
- 使用场景:确定定义的对象的类型时使用
<template>
<div>
<p>姓名:{
{state.name}}</p>
<p>年龄:{
{state.age}} <button @click="state.age++">一年又一年</button></p>
</div>
</template>
<script>
// 1. 导入函数
import { reactive } from "vue";
export default {
setup() {
// 2. 创建响应式数据对象
const state = reactive({ name: 'tom', age: 18 })
// 3. 返回数据
return { state }
}
};
</script>
3. ref函数
- 从
vue
中导出ref
函数 - 在
setup
函数中,使用ref
函数,传入普通数据(简单or复杂),返回一个响应式数据 - 最后
setup
函数返回一个对象,包含该响应式数据即可 - 注意:使用
ref
创建的数据,js
中需要.value
,template
中可省略 ref
可以把简单数据或者复杂数据转换成响应式数据,注意使用加上.value
,不过模板可省略。- 使用场景:任意场景可使用。
<template>
<div>
<p>
计数器:{
{ count }}
<button @click="count++">累加1</button>
<!-- template中使用可省略.value -->
<button @click="increment">累加10</button>
</p>
</div>
</template>
<script>
// 1. 导入函数
import { ref } from "vue";
export default {
setup() {
// 2. 创建响应式数据对象
const count = ref(0);
const increment = () => {
// js中使用需要.value
count.value += 10;
};
// 3. 返回数据
return { count, increment };
},
};
</script>
4. reactive与ref的选择
reactive
可以转换对象成为响应式数据对象,但是不支持简单数据类型。ref
可以转换简单数据类型为响应式数据对象,也支持复杂数据类型,但是操作的时候需要.value
。- 能确定数据是对象且字段名称也确定,可使用
reactive
转成响应式数据,其他一概使用ref
代码参考:
// 1. 明确表单对象有两个字段
const form = reactive({
username: '',
password: ''
})
// 2. 后台返回的数据对象
const data = ref(null)
const res = await axios.get('/user/100')
data.value = res.data
5. setup语法糖
所谓setup的语法糖就是直接在script标签中加入setup,在 script setup
中的顶层变量都可以在模板使用,数据,函数,组件,不需要返回数据函数
体验:
<script setup>
// 显示隐藏
const show = ref(true)
const toggle = () => {
show.value = !show.value
}
// 计数器
const count = ref(0)
const increment = () => {
count.value ++
}
</script>
<template>
<button @click="toggle">显示隐藏图片</button>
<img v-show="show" alt="Vue logo" src="./assets/logo.png" />
<hr />
计数器:{
{ count }} <button @click="increment">累加</button>
</template>
6. computed函数
- 使用
computed
定义计算属性,场景:当需要依赖一个数据得到新的数据使用计算属性 - 从
vue
中导出computed
函数 - 在
setup
函数中,使用computed
函数,传入一个函数,函数返回计算好的数据 - 最后
setup
函数返回一个对象,包含该计算属性数据即可,然后模板内使用
<script setup>
import { ref, computed } from "vue";
const scoreList = ref([80, 100, 90, 70, 60]);
// 计算属性
const betterList = computed(
() => scoreList.value.filter((item) => item >= 90)
);
// 改变数据,计算属性改变
setTimeout(() => {
scoreList.value.push(92, 66);
}, 3000);
</script>
<template>
<div>
<p>分数:{
{ scoreList }}</p>
<p>优秀:{
{ betterList }}</p>
</div>
</template>
7. watch函数
语法:
watch(需要监听的数据,数据改变执行函数,配置对象)
来进行数据的侦听- 数据:单个数据,多个数据,函数返回对象属性,属性复杂需要开启深度监听
- 配置对象:
deep
深度监听immediate
默认执行
- 使用
watch
监听一个响应式数据
const count = ref(0);
// 监听一个响应式数据
// watch(数据, 改变后回调函数)
watch(count, () => {
console.log("count改变了");
});
- 使用
watch
监听多个响应式数据
const count = ref(0);
const user = reactive({
name: "tom",
info: {
gender: "男",
age: 18,
},
});
// 监听多个响应式数据
// watch([数据1, 数据2, ...], 改变后回调函数)
watch([count, user], () => {
console.log("数据改变了");
});
- 使用
watch
监听响应式对象数据中的一个(简单)属性
const user = reactive({
name: "tom",
info: {
gender: "男",
age: 18,
},
});
// 监听响应式对象数据的一个数据,简单类型
// watch(()=>数据, 改变后回调函数)
watch(()=>user.name, () => {
console.log("数据改变了");
});
- 使用
watch
监听响应式对象数据中的一个(复杂)属性,配置深度监听
const user = reactive({
name: "tom",
info: {
gender: "男",
age: 18,
},
});
// 4. 监听响应式对象数据的一个数据,复杂类型
// watch(()=>数据, 改变后回调函数, {deep: true})
watch(
() => user.info,
() => {
console.log("数据改变了");
},
{
// 开启深度监听
deep: true,
}
);
- 使用
watch
监听,配置默认执行
{
// 开启深度监听
deep: true,
// 默认执行一次
immediate: true
}
8. 生命周期函数
使用步骤:
- 先从vue中导入以
on打头
的生命周期钩子函数,生命周期在调用前需要先进行引入 - 在setup函数中调用生命周期函数并传入回调函数
- 生命周期钩子函数可以调用多次 (重点)
- Vue3和vue2的生命周期对比
选项式API下的生命周期函数使用 | 组合式API下的生命周期函数使用 |
---|---|
beforeCreate | 不需要(直接写到setup函数中) |
created | 不需要(直接写到setup函数中) |
beforeMount | onBeforeMount 组件渲染挂载页面之前触发 |
mounted | onMounted 组件渲染完毕触发: 发请求,操作dom,初始化图表... |
beforeUpdate | onBeforeUpdate 组件更新之前触发 |
updated | onUpdated 组件更新之后触发 |
beforeDestroyed | onBeforeUnmount 组件卸载之前触发 |
destroyed | onUnmounted 组件卸载完成触发 |
activated | onActivated 被包含在页面中的组件,会多出两个生命周期钩子函 数。被激活时执行。 |
deactivated | onDeactivated 比如从 A 组件,切换到 B 组件,A 组件消失时执行。 |
9. ref获取DOM元素
-
创建 ref =>
const hRef = ref(null)
-
模板中建立关联 =>
<h1 ref="hRef">我是标题</h1>
-
使用 =>
hRef.value
<script setup>
import { ref } from 'vue'
注意:默认值是null,需要在渲染完毕后访问DOM属性。
const hRef = ref(null)
const clickFn = () => {
hRef.value.innerText = '我不是标题'
}
</script>
<template>
<div>
<h1 ref="hRef">我是标题</h1>
<button @click="clickFn">操作DOM</button>
</div>
</template>
10. ref操作组件-defineExpose
- 使用
<script setup>
的组件是默认关闭的,组件实例使用不到顶层的数据和函数。 - 需要配合
defineExpose
暴露给组件实例使用,暴露的响应式数据会自动解除响应式。
建立一个Form组件 ,defineExpose
暴露出组件的成员
Form组件:
<script setup>
import { ref } from 'vue'
const count = ref(0)
const validate = () => {
console.log('表单校验方法')
}
// 暴露属性给外部组件使用
defineExpose({count, validate})
</script>
<template>
<h3>我是Form组件</h3>
</template>
ref操作组件 :
- 配合
defineExpose
暴露数据和方法,ref获取的组件实例才可以使用
<script setup>
import { ref } from 'vue'
import Form from './components/Form.vue'
// 1. 提供一个ref
const formRef = ref(null)
// 2. 使用组件组件和方法
const fn = () => {
console.log(formRef.value.count)
formRef.value.validate()
}
</script>
<template>
<Form ref="formRef"></Form>
</template>
11. 父传子-defineProps函数
- 父组件提供数据
- 父组件将数据传递给子组件
- 子组件通过
defineProps
进行接收 - 子组件渲染父组件传递的数据
ParentCom.vue父组件
<script setup>
import { ref } from 'vue'
import ChildCom from './components/ChildCom.vue'
const money = ref(100)
const car = ref('玛莎拉蒂')
</script>
<template>
<div>
<h1>我是父组件</h1>
<div>金钱:{
{ money }}</div>
<div>车辆:{
{ car }}</div>
<hr />
<ChildCom :money="money" :car="car"></ChildCom>
</div>
</template>
ChildCom.vue子组件
<script setup>
import { computed } from 'vue'
// defineProps: 接收父组件传递的数据
const props = defineProps({
money: Number,
car: String,
})
// 如果想要在 script 中也操作 props 属性,应该接收返回值
// 使用props接收返回值
console.log(props.money)
</script>
<template>
如果使用 defineProps 接收数据,这个数据只能在模板中渲染
<div>
<h3>我是子组件</h3>
<div>{
{ money }} --- {
{ car }}</div>
</div>
</template>
- 如果使用
defineProps
接收数据,这个数据只能在模板中渲染 - 如果想要在
script
中也操作props
属性,应该接收返回值
12. 子传父-defineEmits函数
- 子组件通过
defineEmits
获取emit
函数(因为没有this) - 子组件通过
emit
触发事件,并且传递数据 - 父组件提供方法
- 父组件通过自定义事件的方式给子组件注册事件
ChildCom.vue 子组件
defineEmits
获取emit
函数,且组件需要触发的事件需要显性声明出来
<script setup>
defineProps({
money: Number,
car: String,
})
// 得到emit函数,显性声明事件名称
const emit = defineEmits(['changeMoney'])
const change = () => {
emit('changeMoney', 10)
}
</script>
PrarentCom.vue父组件
<script setup>
import { ref } from 'vue'
import ChildCom from './components/ChildCom.vue'
const money = ref(100)
const car = ref('玛莎拉蒂')
const changeMoney = (num) => {
money.value = money.value - num
}
</script>
<ChildCom :money="money" :car="car" @changeMoney="changeMoney"></ChildCom>
13. 跨级组件通讯provide与inject函数
-
provide和inject是解决跨级组件通讯的方案
- provide 提供后代组件需要依赖的数据或函数
- inject 注入(获取)provide提供的数据或函数
祖先组件:App.vue
import { provide, ref } from 'vue';
import ParentCom from './ParentCom.vue';
// 1. app组件数据传递给child
const count = ref(0);
provide('count', count);
// 2. app组件函数传递给child,调用的时候可以回传数据
const updateCount = (num) => {
count.value += num;
};
provide('updateCount', updateCount);
后代子级组件:ChildCom.vue
<script setup>
import { inject } from 'vue';
const count = inject('count');
const updateCount = inject('updateCount');
</script>
<template>
<div class="child-page" style="padding: 50px; border: 10px solid #ccc">
child 组件 {
{ count }} <button @click="updateCount(100)">修改count</button>
</div>
</template>
14. 保持响应式-toRefs函数
- 在使用reactive创建的响应式数据被展开或解构的时候使用toRefs保持响应式
- 使用解构响应式数据,展开响应式数据踩坑
基础写法:
<script setup>
import { reactive } from "vue";
const user = reactive({ name: "tom", age: 18 });
</script>
<template>
<div>
<p>姓名:{
{ user.name }}</p>
<p>年龄:{
{ user.age }} <button @click="user.age++">一年又一年</button></p>
</div>
</template>
解构写法: 响应式丢失
<script setup>
import { reactive } from "vue";
const { name, age } = reactive({ name: "tom", age: 18 });
</script>
<template>
<div>
<p>姓名:{
{ name }}</p>
<!-- 响应式丢失 -->
<p>年龄:{
{ age }} <button @click="age++">一年又一年</button></p>
</div>
</template>
- 使用
toRefs
处理响应式数据,爬坑
import { reactive, toRefs } from "vue";
const user = reactive({ name: "tom", age: 18 });
const { name, age } = toRefs(user)
toRefs
函数的作用,与使用场景
- 作用:把对象中的每一个属性做一次包装成为响应式数据
- 响应式数据展开的时候使用,解构响应式数据的时候使用