mirror of
https://github.com/Estom/notes.git
synced 2026-02-03 02:23:31 +08:00
vue3笔记和源码补充
This commit is contained in:
28
Vue/code/01.源码/App.vue
Normal file
28
Vue/code/01.源码/App.vue
Normal file
@@ -0,0 +1,28 @@
|
||||
<template>
|
||||
<img alt="Vue logo" src="./assets/logo.png" />
|
||||
<HelloWorld msg="Welcome to Your Vue.js + TypeScript App" />
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent } from 'vue'
|
||||
// defineComponent函数,目的是定义一个组件,内部可以传入一个配置对象
|
||||
import HelloWorld from './components/HelloWorld.vue'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
components: {
|
||||
HelloWorld
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style>
|
||||
#app {
|
||||
font-family: Avenir, Helvetica, Arial, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
text-align: center;
|
||||
color: #2c3e50;
|
||||
margin-top: 60px;
|
||||
}
|
||||
</style>
|
||||
BIN
Vue/code/01.源码/assets/logo.png
Normal file
BIN
Vue/code/01.源码/assets/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 6.7 KiB |
61
Vue/code/01.源码/components/HelloWorld.vue
Normal file
61
Vue/code/01.源码/components/HelloWorld.vue
Normal file
@@ -0,0 +1,61 @@
|
||||
<template>
|
||||
<div class="hello">
|
||||
<h1>{{ msg }}</h1>
|
||||
<p>
|
||||
For a guide and recipes on how to configure / customize this project,<br>
|
||||
check out the
|
||||
<a href="https://cli.vuejs.org" target="_blank" rel="noopener">vue-cli documentation</a>.
|
||||
</p>
|
||||
<h3>Installed CLI Plugins</h3>
|
||||
<ul>
|
||||
<li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel" target="_blank" rel="noopener">babel</a></li>
|
||||
<li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-typescript" target="_blank" rel="noopener">typescript</a></li>
|
||||
<li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-eslint" target="_blank" rel="noopener">eslint</a></li>
|
||||
</ul>
|
||||
<h3>Essential Links</h3>
|
||||
<ul>
|
||||
<li><a href="https://vuejs.org" target="_blank" rel="noopener">Core Docs</a></li>
|
||||
<li><a href="https://forum.vuejs.org" target="_blank" rel="noopener">Forum</a></li>
|
||||
<li><a href="https://chat.vuejs.org" target="_blank" rel="noopener">Community Chat</a></li>
|
||||
<li><a href="https://twitter.com/vuejs" target="_blank" rel="noopener">Twitter</a></li>
|
||||
<li><a href="https://news.vuejs.org" target="_blank" rel="noopener">News</a></li>
|
||||
</ul>
|
||||
<h3>Ecosystem</h3>
|
||||
<ul>
|
||||
<li><a href="https://router.vuejs.org" target="_blank" rel="noopener">vue-router</a></li>
|
||||
<li><a href="https://vuex.vuejs.org" target="_blank" rel="noopener">vuex</a></li>
|
||||
<li><a href="https://github.com/vuejs/vue-devtools#vue-devtools" target="_blank" rel="noopener">vue-devtools</a></li>
|
||||
<li><a href="https://vue-loader.vuejs.org" target="_blank" rel="noopener">vue-loader</a></li>
|
||||
<li><a href="https://github.com/vuejs/awesome-vue" target="_blank" rel="noopener">awesome-vue</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent } from 'vue';
|
||||
|
||||
export default defineComponent({
|
||||
name: 'HelloWorld',
|
||||
props: {
|
||||
msg: String,
|
||||
},
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- Add "scoped" attribute to limit CSS to this component only -->
|
||||
<style scoped>
|
||||
h3 {
|
||||
margin: 40px 0 0;
|
||||
}
|
||||
ul {
|
||||
list-style-type: none;
|
||||
padding: 0;
|
||||
}
|
||||
li {
|
||||
display: inline-block;
|
||||
margin: 0 10px;
|
||||
}
|
||||
a {
|
||||
color: #42b983;
|
||||
}
|
||||
</style>
|
||||
4
Vue/code/01.源码/main.ts
Normal file
4
Vue/code/01.源码/main.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
|
||||
createApp(App).mount('#app')
|
||||
6
Vue/code/01.源码/shims-vue.d.ts
vendored
Normal file
6
Vue/code/01.源码/shims-vue.d.ts
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
/* eslint-disable */
|
||||
declare module '*.vue' {
|
||||
import type { DefineComponent } from 'vue'
|
||||
const component: DefineComponent<{}, {}, any>
|
||||
export default component
|
||||
}
|
||||
20
Vue/code/02.setup初识/App.vue
Normal file
20
Vue/code/02.setup初识/App.vue
Normal file
@@ -0,0 +1,20 @@
|
||||
<template>
|
||||
<div>setup</div>
|
||||
<h1>{{ number }}</h1>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent } from 'vue'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
// setup是组合API中第一个要使用的函数
|
||||
setup() {
|
||||
const number = 10
|
||||
|
||||
return {
|
||||
number
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
56
Vue/code/03.setup和ref的基本使用/App.vue
Normal file
56
Vue/code/03.setup和ref的基本使用/App.vue
Normal file
@@ -0,0 +1,56 @@
|
||||
<template>
|
||||
<h2>setup和ref的基本使用</h2>
|
||||
<h3>{{ count }}</h3>
|
||||
<button @click="updateCount">更新数据</button>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, ref } from 'vue'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
// 需求:页面打开后可以直接看到一个数据,点击按钮后,该数据可以发生变化
|
||||
// vue2的方式实现
|
||||
// data() {
|
||||
// return {
|
||||
// count: 0 // 属性
|
||||
// }
|
||||
// },
|
||||
// methods: {
|
||||
// updateCount() {
|
||||
// // 方法
|
||||
// this.count++
|
||||
// }
|
||||
// },
|
||||
|
||||
// vue3的方式实现
|
||||
// setup是组合API的入口函数
|
||||
setup() {
|
||||
// console.log('第一次')
|
||||
// 变量
|
||||
// let count = 0 // 此时的数据并不是响应式的数据(响应式数据:数据变化,页面跟着渲染变化)
|
||||
|
||||
// ref是一个函数,作用:定义一个响应式的数据,返回的是一个Ref对象,
|
||||
// 对象中有一个value属性,如果需要对数据进行操作,需要使用该Ref对象调用value属性的方式进行数据的操作
|
||||
// html模版中是不需要使用.value属性的写法
|
||||
// TODO 一般用来定义一个基本类型的响应式数据
|
||||
// count 的类型 Ref类型
|
||||
const count = ref(0)
|
||||
console.log(count)
|
||||
// 方法
|
||||
function updateCount() {
|
||||
console.log('=====')
|
||||
// 报错的原因:count是一个Ref对象,对象是不能进行++的操作
|
||||
// count++
|
||||
count.value++
|
||||
}
|
||||
// 返回的是一个对象
|
||||
return {
|
||||
// 属性
|
||||
count,
|
||||
// 方法
|
||||
updateCount
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
78
Vue/code/04.reactive基本使用/App.vue
Normal file
78
Vue/code/04.reactive基本使用/App.vue
Normal file
@@ -0,0 +1,78 @@
|
||||
<template>
|
||||
<h2>reactive的使用</h2>
|
||||
<h3>名字:{{ user.name }}</h3>
|
||||
<h3>年龄:{{ user.age }}</h3>
|
||||
<h3>性别:{{ user.gender }}</h3>
|
||||
<h3>媳妇:{{ user.wife }}</h3>
|
||||
<hr />
|
||||
<button @click="updateUser">更新数据</button>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, reactive } from 'vue'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
// 需求:显示用户的相关信息,点击按钮,可以更新用户的相关信息数据
|
||||
|
||||
/*
|
||||
reactive
|
||||
作用: 定义多个数据的响应式
|
||||
const proxy = reactive(obj): 接收一个普通对象然后返回该普通对象的响应式代理器对象
|
||||
响应式转换是“深层的”:会影响对象内部所有嵌套的属性
|
||||
内部基于 ES6 的 Proxy 实现,通过代理对象操作源对象内部数据都是响应式的
|
||||
*/
|
||||
setup() {
|
||||
// const obj: any = { // 为了在使用obj.gender='男' 的时候不出现这种错误的提示信息才这么书写
|
||||
const obj = {
|
||||
name: '小明',
|
||||
age: 20,
|
||||
wife: {
|
||||
name: '小甜甜',
|
||||
age: 18,
|
||||
cars: ['奔驰', '宝马', '奥迪']
|
||||
}
|
||||
}
|
||||
// 把数据变成响应式的数据
|
||||
// 返回的是一个Proxy的代理对象,被代理的目标对象就是obj对象
|
||||
// user现在是代理对象,obj是目标对象
|
||||
// user对象的类型是Proxy
|
||||
const user = reactive<any>(obj)
|
||||
console.log(user)
|
||||
|
||||
const updateUser = () => {
|
||||
// 直接使用目标对象的方式来更新目标对象中的成员的值,是不可能的,
|
||||
// 只能使用代理对象的方式来更新数据(响应式数据)
|
||||
// obj.name += '==='
|
||||
// 下面的可以
|
||||
// user.name += '=='
|
||||
// user.age += 2
|
||||
// user.wife.name += '++'
|
||||
// user.wife.cars[0] = '玛莎拉蒂'
|
||||
|
||||
// user---->代理对象,user---->目标对象
|
||||
// user对象或者obj对象添加一个新的属性,哪一种方式会影响界面的更新
|
||||
// obj.gender = '男' // 这种方式,界面没有更新渲染
|
||||
// user.gender = '男' // 这种方式,界面可以更新渲染,而且这个数据最终也添加到了obj对象上了
|
||||
// user对象或者obj对象中移除一个已经存在的属性,哪一种方式会影响界面的更新
|
||||
// delete obj.age // 界面没有更新渲染,obj中确实没有了age这个属性
|
||||
// delete user.age // 界面更新渲染了,obj中确实没有了age这个属性
|
||||
|
||||
// TODO 总结: 如果操作代理对象,目标对象中的数据也会随之变化,同时如果想要在操作数据的时候,界面也要跟着重新更新渲染,那么也是操作代理对象
|
||||
|
||||
// 通过当前的代理对象找到该对象中的某个属性,更改该属性中的某个数组的数据
|
||||
// user.wife.cars[1] = '玛莎拉蒂'
|
||||
|
||||
// 通过当前的代理对象把目标对象中的某个数组属性添加一个新的属性
|
||||
user.wife.cars[3] = '奥拓'
|
||||
console.log(obj)
|
||||
console.log(user)
|
||||
}
|
||||
|
||||
return {
|
||||
user,
|
||||
updateUser
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
57
Vue/code/05.vue3的响应式数据的核心原理/index.html
Normal file
57
Vue/code/05.vue3的响应式数据的核心原理/index.html
Normal file
@@ -0,0 +1,57 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
|
||||
<title>vue3的响应式数据的核心原理</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<script type="text/javascript">
|
||||
// 目标对象
|
||||
const user = {
|
||||
name: '佐助',
|
||||
age: 20,
|
||||
wife: {
|
||||
name: '小樱',
|
||||
age: 19
|
||||
}
|
||||
}
|
||||
// 把目标对象变成代理对象
|
||||
// 参数1: user---->target目标对象
|
||||
// 参数2: handler---->处理器对象,用来监视数据,及数据的操作
|
||||
const proxyUser = new Proxy(user, {
|
||||
// 获取目标对象的某个属性值
|
||||
get(target, prop) {
|
||||
console.log('get方法调用了')
|
||||
return Reflect.get(target, prop)
|
||||
},
|
||||
// 修改目标对象的属性值/为目标对象添加新的属性
|
||||
set(target, prop, val) {
|
||||
console.log('set方法调用了')
|
||||
return Reflect.set(target, prop, val)
|
||||
},
|
||||
// 删除目标对象上的某个属性
|
||||
deleteProperty(target, prop) {
|
||||
console.log('delete方法调用了')
|
||||
return Reflect.deleteProperty(target, prop)
|
||||
}
|
||||
})
|
||||
|
||||
// 通过代理对象获取目标对象中的某个属性值
|
||||
console.log(proxyUser.name)
|
||||
// 通过代理对象更新目标对象上的某个属性值
|
||||
proxyUser.name = '鸣人'
|
||||
console.log(user)
|
||||
// 通过代理对象向目标对象中添加一个新的属性
|
||||
proxyUser.gender = '男'
|
||||
console.log(user)
|
||||
delete proxyUser.name
|
||||
console.log(user)
|
||||
// 更新目标对象中的某个属性对象中的属性值
|
||||
proxyUser.wife.name = '雏田'
|
||||
console.log(user)
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
31
Vue/code/06.setup的细节问题/App.vue
Normal file
31
Vue/code/06.setup的细节问题/App.vue
Normal file
@@ -0,0 +1,31 @@
|
||||
<template>
|
||||
<h2>App父级组件</h2>
|
||||
<h3>msg:{{ msg }}</h3>
|
||||
<button @click="msg += '==='">更新数据</button>
|
||||
<Child msg2="真香" :msg="msg" @xxx="xxx" />
|
||||
</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('how old are you?')
|
||||
|
||||
function xxx(txt: string) {
|
||||
console.log('接收子组件数据')
|
||||
msg.value += txt
|
||||
}
|
||||
|
||||
return {
|
||||
msg,
|
||||
xxx
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
79
Vue/code/06.setup的细节问题/components/Child.vue
Normal file
79
Vue/code/06.setup的细节问题/components/Child.vue
Normal file
@@ -0,0 +1,79 @@
|
||||
<template>
|
||||
<h2>Child</h2>
|
||||
<h3>msg:{{ msg }}</h3>
|
||||
<!-- <h3>count:{{ count }}</h3> -->
|
||||
<button @click="emitXxx">分发事件</button>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent } from 'vue'
|
||||
export default defineComponent({
|
||||
name: 'Child',
|
||||
props: ['msg'],
|
||||
emits: ['xxx'],
|
||||
// setup细节问题:
|
||||
|
||||
// 1. setup执行的时机
|
||||
// setup是在beforeCreate生命周期回调之前就执行了,而且就执行一次
|
||||
// 由此可以推断出:setup在执行的时候,当前的组件还没有创建出来,也就意味着:组件实例对象this根本就不能用
|
||||
// this是undefined,说明,就不能通过this再去调用data/computed/methods/props中的相关内容了
|
||||
// 其实所有的composition API相关回调函数中也都不可以
|
||||
|
||||
// 2. setup的返回值
|
||||
// setup中的返回值是一个对象,内部的属性和方法是给html模版使用的
|
||||
// setup中的对象内部的属性和data函数中的return对象的属性都可以在html模版中使用
|
||||
// setup中的对象中的属性和data函数中的对象中的属性会合并为组件对象的属性
|
||||
// setup中的对象中的方法和methods对象中的方法会合并为组件对象的方法
|
||||
// 在Vue3中尽量不要混合的使用data和setup及methods和setup
|
||||
// 一般不要混合使用: methods中可以访问setup提供的属性和方法, 但在setup方法中不能访问data和methods
|
||||
// setup不能是一个async函数: 因为返回值不再是return的对象, 而是promise, 模板看不到return对象中的属性数据
|
||||
// beforeCreate() {
|
||||
// console.log('beforeCreate执行了')
|
||||
// },
|
||||
// 界面渲染完毕
|
||||
// mounted() {},
|
||||
// setup(props, context) {
|
||||
setup(props, { attrs, slots, emit }) {
|
||||
// props参数,是一个对象,里面有父级组件向子级组件传递的数据,并且是在子级组件中使用props接收到的所有的属性
|
||||
// 包含props配置声明且传入了的所有属性的对象
|
||||
// console.log(props.msg)
|
||||
// console.log(props)
|
||||
// console.log(context)
|
||||
// console.log(context.attrs)
|
||||
// console.log(context.emit)
|
||||
// context参数,是一个对象,里面有attrs对象(获取当前组件标签上的所有的属性的对象,但是该属性是在props中没有声明接收的所有的尚需经的对象),emit方法(分发事件的),slots对象(插槽)
|
||||
// 包含没有在props配置中声明的属性的对象, 相当于 this.$attrs
|
||||
// console.log(context.attrs.msg2)
|
||||
// console.log('=============')
|
||||
|
||||
const showMsg1 = () => {
|
||||
console.log('setup中的showMsg1方法')
|
||||
}
|
||||
console.log('setup执行了', this)
|
||||
// 按钮的点击事件的回调函数
|
||||
function emitXxx() {
|
||||
// context.emit('xxx', '++')
|
||||
emit('xxx', '++')
|
||||
}
|
||||
return {
|
||||
showMsg1,
|
||||
emitXxx
|
||||
}
|
||||
}
|
||||
// data() {
|
||||
// return {
|
||||
// count: 10
|
||||
// }
|
||||
// },
|
||||
// // 界面渲染后的生命周期回调
|
||||
// mounted() {
|
||||
// console.log(this)
|
||||
// },
|
||||
// // 方法的
|
||||
// methods: {
|
||||
// showMsg2() {
|
||||
// console.log('methods中的showMsg方法')
|
||||
// }
|
||||
// }
|
||||
})
|
||||
</script>
|
||||
55
Vue/code/07.ref和reactive的细节问题/App.vue
Normal file
55
Vue/code/07.ref和reactive的细节问题/App.vue
Normal file
@@ -0,0 +1,55 @@
|
||||
<template>
|
||||
<h2>reactive和ref的细节问题</h2>
|
||||
<h3>m1:{{ m1 }}</h3>
|
||||
<h3>m2:{{ m2 }}</h3>
|
||||
<h3>m3:{{ m3 }}</h3>
|
||||
<hr />
|
||||
<button @click="update">更新数据</button>
|
||||
</template>
|
||||
<script lang="ts">
|
||||
import { defineComponent, ref, reactive } from 'vue'
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
// 是Vue3的 composition API中2个最重要的响应式API(ref和reactive)
|
||||
// ref用来处理基本类型数据, reactive用来处理对象(递归深度响应式)
|
||||
// 如果用ref对象/数组, 内部会自动将对象/数组转换为reactive的代理对象
|
||||
// ref内部: 通过给value属性添加getter/setter来实现对数据的劫持
|
||||
// reactive内部: 通过使用Proxy来实现对对象内部所有数据的劫持, 并通过Reflect操作对象内部数据
|
||||
// ref的数据操作: 在js中要.value, 在模板中不需要(内部解析模板时会自动添加.value)
|
||||
|
||||
setup() {
|
||||
// 通过ref的方式设置的数据
|
||||
const m1 = ref('abc')
|
||||
const m2 = reactive({
|
||||
name: '小明',
|
||||
wife: {
|
||||
name: '小红'
|
||||
}
|
||||
})
|
||||
// ref也可以传入对象吗
|
||||
const m3 = ref({
|
||||
name: '小明',
|
||||
wife: {
|
||||
name: '小红'
|
||||
}
|
||||
})
|
||||
// 更新数据
|
||||
const update = () => {
|
||||
// TODO ref中如果放入的是一个对象,那么是经过了reactive的处理,形成了一个Proxy类型的对象
|
||||
console.log(m2)
|
||||
console.log(m3)
|
||||
m1.value += '==='
|
||||
m2.wife.name += '==='
|
||||
m3.value.name += '==='
|
||||
m3.value.wife.name += '==='
|
||||
console.log(m3.value.wife)
|
||||
}
|
||||
return {
|
||||
m1,
|
||||
m2,
|
||||
m3,
|
||||
update
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
97
Vue/code/08.watch和watchEffect/App.vue
Normal file
97
Vue/code/08.watch和watchEffect/App.vue
Normal file
@@ -0,0 +1,97 @@
|
||||
<template>
|
||||
<h2>计算属性和监视</h2>
|
||||
<fieldset>
|
||||
<legend>姓名操作</legend>
|
||||
姓氏:<input type="text" placeholder="请输入姓氏" v-model="user.firstName" /><br />
|
||||
名字:<input type="text" placeholder="请输入名字" v-model="user.lastName" /><br />
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>计算属性和监视的演示</legend>
|
||||
姓名:<input type="text" placeholder="显示姓名" v-model="fullName1" /><br />
|
||||
姓名:<input type="text" placeholder="显示姓名" v-model="fullName2" /><br />
|
||||
姓名:<input type="text" placeholder="显示姓名" v-model="fullName3" /><br />
|
||||
</fieldset>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, reactive, computed, watch, ref, watchEffect } from 'vue'
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
setup() {
|
||||
const user = reactive({
|
||||
firstName: '东方',
|
||||
lastName: '不败'
|
||||
})
|
||||
|
||||
// 通过计算属性的方式,实现第一个姓名的显示
|
||||
// vue3中的计算属性
|
||||
// 计算属性的函数中如果只传入一个回调函数,表示的是get
|
||||
// 第一个姓名:
|
||||
// 返回的是一个Ref类型的对象
|
||||
const fullName1 = computed(() => {
|
||||
return user.firstName + '_' + user.lastName
|
||||
})
|
||||
console.log(fullName1)
|
||||
|
||||
// 第二个姓名: 传入 get set 两个方法,接收的是一个对象
|
||||
const fullName2 = computed({
|
||||
get() {
|
||||
return user.firstName + '_' + user.lastName
|
||||
},
|
||||
set(val: string) {
|
||||
// console.log('=====',val)
|
||||
const names = val.split('_')
|
||||
user.firstName = names[0]
|
||||
user.lastName = names[1]
|
||||
}
|
||||
})
|
||||
console.log(fullName2)
|
||||
|
||||
// 监视 -- 监视指定的数据
|
||||
// 第三个姓名:
|
||||
const fullName3 = ref('东方_不败')
|
||||
// watch(
|
||||
// user,
|
||||
// ({ firstName, lastName }) => {
|
||||
// fullName3.value = firstName + '_' + lastName
|
||||
// },
|
||||
// {
|
||||
// immediate: true,
|
||||
// deep: true
|
||||
// }
|
||||
// )
|
||||
// immediate 默认会执行一次watch,deep 深度监视
|
||||
|
||||
// 监视,不需要配置immediate,本身默认就会进行监视,(默认执行一次)
|
||||
// watchEffect(() => {
|
||||
// fullName3.value = user.firstName + '_' + user.lastName
|
||||
// })
|
||||
|
||||
// 监视fullName3的数据,改变firstName和lastName
|
||||
// watchEffect(() => {
|
||||
// const names = fullName3.value.split('_')
|
||||
// user.firstName = names[0]
|
||||
// user.lastName = names[1]
|
||||
// })
|
||||
|
||||
// watch---可以监视多个数据的
|
||||
// watch([user.firstName, user.lastName, fullName3], () => {
|
||||
// // 这里的代码就没有执行, fullName3是响应式的数据, 但是, user.firstName、user.lastName不是响应式的数据
|
||||
// console.log('====')
|
||||
// })
|
||||
|
||||
// 当我们使用watch监视非响应式的数据的时候,代码需要改一下
|
||||
watch([() => user.firstName, () => user.lastName, fullName3], () => {
|
||||
// 这里的代码就没有执行,fullName3是响应式的数据,但是,user.firstName,user.lastName不是响应式的数据
|
||||
console.log('====')
|
||||
})
|
||||
|
||||
return {
|
||||
user,
|
||||
fullName1,
|
||||
fullName2,
|
||||
fullName3
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
25
Vue/code/09.生命周期/App.vue
Normal file
25
Vue/code/09.生命周期/App.vue
Normal file
@@ -0,0 +1,25 @@
|
||||
<template>
|
||||
<h2>App父级组件</h2>
|
||||
<button @click="isShow = !isShow">切换显示</button>
|
||||
<hr />
|
||||
<Child v-if="isShow" />
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, ref } from 'vue'
|
||||
import Child from './components/Child.vue'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
// 注册组件
|
||||
components: {
|
||||
Child
|
||||
},
|
||||
setup() {
|
||||
const isShow = ref(true)
|
||||
return {
|
||||
isShow
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
70
Vue/code/09.生命周期/components/Child.vue
Normal file
70
Vue/code/09.生命周期/components/Child.vue
Normal file
@@ -0,0 +1,70 @@
|
||||
<template>
|
||||
<h2>Child子级组件</h2>
|
||||
<h4>msg:{{ msg }}</h4>
|
||||
<button @click="update">更新数据</button>
|
||||
</template>
|
||||
<script lang="ts">
|
||||
import { defineComponent, ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue'
|
||||
export default defineComponent({
|
||||
name: 'Child',
|
||||
// vue2.x中的生命周期钩子
|
||||
beforeCreate() {
|
||||
console.log('2.x中的beforeCreate...')
|
||||
},
|
||||
created() {
|
||||
console.log('2.x中的created...')
|
||||
},
|
||||
beforeMount() {
|
||||
console.log('2.x中的beforeMount...')
|
||||
},
|
||||
mounted() {
|
||||
console.log('2.x中的mounted...')
|
||||
},
|
||||
beforeUpdate() {
|
||||
console.log('2.x中的beforeUpdate...')
|
||||
},
|
||||
updated() {
|
||||
console.log('2.x中的updated...')
|
||||
},
|
||||
// vue2.x中的beforeDestroy和destroyed这两个生命周期回调已经在vue3中改名了,所以,不能再使用了
|
||||
beforeUnmount() {
|
||||
console.log('2.x中的beforeUnmount...')
|
||||
},
|
||||
unmounted() {
|
||||
console.log('2.x中的unmounted...')
|
||||
},
|
||||
|
||||
setup() {
|
||||
console.log('3.0中的setup')
|
||||
// 响应式的数据
|
||||
const msg = ref('abc')
|
||||
// 按钮点击事件的回调
|
||||
const update = () => {
|
||||
msg.value += '==='
|
||||
}
|
||||
onBeforeMount(() => {
|
||||
console.log('3.0中的onBeforeMount')
|
||||
})
|
||||
onMounted(() => {
|
||||
console.log('3.0中的onMounted')
|
||||
})
|
||||
onBeforeUpdate(() => {
|
||||
console.log('3.0中的onBeforeUpdate')
|
||||
})
|
||||
onUpdated(() => {
|
||||
console.log('3.0中的onUpdated')
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
console.log('3.0中的onBeforeUnmount')
|
||||
})
|
||||
onUnmounted(() => {
|
||||
console.log('3.0中的onUnmounted')
|
||||
})
|
||||
|
||||
return {
|
||||
msg,
|
||||
update
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
BIN
Vue/code/09.生命周期/lifecycle/lifecycle2.png
Normal file
BIN
Vue/code/09.生命周期/lifecycle/lifecycle2.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 49 KiB |
BIN
Vue/code/09.生命周期/lifecycle/lifecycle3.png
Normal file
BIN
Vue/code/09.生命周期/lifecycle/lifecycle3.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 399 KiB |
64
Vue/code/10.自定义hooks/App.vue
Normal file
64
Vue/code/10.自定义hooks/App.vue
Normal file
@@ -0,0 +1,64 @@
|
||||
<template>
|
||||
<h2>自定义hook函数操作</h2>
|
||||
<h2>x:{{ x }},y:{{ y }}</h2>
|
||||
<h3 v-if="loading">正在加载中....</h3>
|
||||
<h3 v-else-if="errorMsg">错误信息:{{ errorMsg }}</h3>
|
||||
|
||||
<!-- 对象数据 -->
|
||||
<!-- <ul v-else>
|
||||
<li>id: {{ data.id }}</li>
|
||||
<li>address: {{ data.address }}</li>
|
||||
<li>distance: {{ data.distance }}</li>
|
||||
</ul>
|
||||
<hr /> -->
|
||||
<!--数组数据-->
|
||||
<ul v-for="item in data" :key="item.id">
|
||||
<li>id:{{ item.id }}</li>
|
||||
<li>title:{{ item.title }}</li>
|
||||
<li>price:{{ item.price }}</li>
|
||||
</ul>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, watch } from 'vue'
|
||||
import useMousePosition from './hooks/useMousePosition'
|
||||
import useRequest from './hooks/useRequest'
|
||||
|
||||
// 定义接口,约束对象的类型
|
||||
interface AddressData {
|
||||
id: number
|
||||
address: string
|
||||
distance: string
|
||||
}
|
||||
interface ProductsData {
|
||||
id: number
|
||||
address: string
|
||||
distance: string
|
||||
}
|
||||
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
// 需求1:用户在页面中点击页面,把点击的位置的横纵坐标收集起来并展示出来
|
||||
setup() {
|
||||
const { x, y } = useMousePosition()
|
||||
// 发送请求
|
||||
// const { loading, data, errorMsg } = useRequest<AddressData>('/data/address.json') // 获取对象数据
|
||||
const { loading, data, errorMsg } = useRequest<ProductsData[]>('/data/products.json') // 获取数组数据
|
||||
|
||||
// 监视
|
||||
watch(data, () => {
|
||||
if (data.value) {
|
||||
console.log(data.value.length)
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
x,
|
||||
y,
|
||||
loading,
|
||||
data,
|
||||
errorMsg
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
28
Vue/code/10.自定义hooks/hooks/useMousePosition.ts
Normal file
28
Vue/code/10.自定义hooks/hooks/useMousePosition.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { ref, onMounted, onUnmounted } from 'vue'
|
||||
|
||||
export default function() {
|
||||
const x = ref(0)
|
||||
const y = ref(0)
|
||||
|
||||
// 点击事件的回调函数
|
||||
const onHandlerClick = (event: MouseEvent) => {
|
||||
x.value = event.pageX
|
||||
y.value = event.pageY
|
||||
}
|
||||
|
||||
// 页面已经加载完毕了,再进行点击的操作
|
||||
// 页面加载完毕的生命周期组合API
|
||||
onMounted(() => {
|
||||
window.addEventListener('click', onHandlerClick)
|
||||
})
|
||||
|
||||
// 页面卸载之前的生命周期组合API
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('click', onHandlerClick)
|
||||
})
|
||||
|
||||
return {
|
||||
x,
|
||||
y
|
||||
}
|
||||
}
|
||||
29
Vue/code/10.自定义hooks/hooks/useRequest.ts
Normal file
29
Vue/code/10.自定义hooks/hooks/useRequest.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
|
||||
// 发送 ajax 请求
|
||||
export default function<T>(url: string) {
|
||||
// 加载的状态
|
||||
const loading = ref(true)
|
||||
// 请求成功的数据
|
||||
const data = ref<T | null>(null) // 坑
|
||||
// 错误信息
|
||||
const errorMsg = ref('')
|
||||
|
||||
axios
|
||||
.get(url)
|
||||
.then(response => {
|
||||
loading.value = false
|
||||
data.value = response.data
|
||||
})
|
||||
.catch(error => {
|
||||
loading.value = false
|
||||
errorMsg.value = error.message || '未知错误'
|
||||
})
|
||||
|
||||
return {
|
||||
loading,
|
||||
data,
|
||||
errorMsg
|
||||
}
|
||||
}
|
||||
67
Vue/code/11.toRefs/App.vue
Normal file
67
Vue/code/11.toRefs/App.vue
Normal file
@@ -0,0 +1,67 @@
|
||||
<template>
|
||||
<h2>toRefs的使用</h2>
|
||||
<!-- <h3>name:{{ state.name }}</h3>
|
||||
<h3>age:{{ state.age }}</h3> -->
|
||||
|
||||
<h3>name:{{ name }}</h3>
|
||||
<h3>age:{{ age }}</h3>
|
||||
|
||||
<h3>name2:{{ name2 }}</h3>
|
||||
<h3>age2:{{ age2 }}</h3>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, reactive, toRefs } from 'vue'
|
||||
|
||||
/*
|
||||
toRefs:
|
||||
把一个响应式对象转换成普通对象,该普通对象的每个 property 都是一个 ref
|
||||
将响应式对象中所有属性包装为ref对象, 并返回包含这些ref对象的普通对象
|
||||
应用: 当从合成函数返回响应式对象时,toRefs 非常有用,
|
||||
这样消费组件就可以在不丢失响应式的情况下对返回的对象进行分解使用
|
||||
*/
|
||||
|
||||
function useFeatureX() {
|
||||
const state = reactive({
|
||||
name2: '自来也',
|
||||
age2: 47
|
||||
})
|
||||
return {
|
||||
...toRefs(state)
|
||||
}
|
||||
}
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
setup() {
|
||||
const state = reactive({
|
||||
name: '自来也',
|
||||
age: 47
|
||||
})
|
||||
|
||||
// toRefs可以把一个响应式对象转换成普通对象,该普通对象的每个 property 都是一个 ref
|
||||
const state2 = toRefs(state)
|
||||
const { name, age } = toRefs(state)
|
||||
console.log(state2)
|
||||
// 定时器,更新数据,(如果数据变化了,界面也会随之变化,肯定是响应式的数据)
|
||||
setInterval(() => {
|
||||
console.log(123)
|
||||
// state.name += '--' // 响应式
|
||||
// state2.name.value += '---' // 响应式
|
||||
name.value += '_____'
|
||||
}, 1500)
|
||||
|
||||
const { name2, age2 } = useFeatureX()
|
||||
|
||||
return {
|
||||
// state,
|
||||
// 下面的方式不行啊
|
||||
// ...state // 不是响应式的数据了---->{name:'自来也',age:47}
|
||||
// ...state2, // toRefs返回来的对象
|
||||
name,
|
||||
age,
|
||||
name2,
|
||||
age2
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
26
Vue/code/12.ref获取页面元素/App.vue
Normal file
26
Vue/code/12.ref获取页面元素/App.vue
Normal file
@@ -0,0 +1,26 @@
|
||||
<template>
|
||||
<h2>ref的另一个作用:可以获取页面中的元素</h2>
|
||||
<input type="text" ref="inputRef" />
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, onMounted, ref } from 'vue'
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
|
||||
// 需求:当页面加载完毕后,页面中的文本框可以直接获取焦点(自动获取焦点)
|
||||
|
||||
setup() {
|
||||
// 默认是空的,页面加载完毕,说明组件已经存在了,获取文本框元素
|
||||
const inputRef = ref<HTMLElement | null>(null)
|
||||
|
||||
// 页面加载后的生命周期组合API
|
||||
onMounted(() => {
|
||||
inputRef.value && inputRef.value.focus() // 自动获取焦点
|
||||
})
|
||||
return {
|
||||
inputRef
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
87
Vue/code/13.shallowReactive和shallowRef/App.vue
Normal file
87
Vue/code/13.shallowReactive和shallowRef/App.vue
Normal file
@@ -0,0 +1,87 @@
|
||||
<template>
|
||||
<h2>shallowReactive和shallowRef</h2>
|
||||
<h3>m1:{{ m1 }}</h3>
|
||||
<h3>m2:{{ m2 }}</h3>
|
||||
<h3>m3:{{ m3 }}</h3>
|
||||
<h3>m4:{{ m4 }}</h3>
|
||||
<hr />
|
||||
<button @click="update">更新数据</button>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, reactive, ref, shallowReactive, shallowRef } from 'vue'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
setup() {
|
||||
// 深度劫持(深监视)----深度响应式
|
||||
const m1 = reactive({
|
||||
name: '鸣人',
|
||||
age: 20,
|
||||
car: {
|
||||
name: '奔驰',
|
||||
color: 'red',
|
||||
city: {
|
||||
name: 'bj'
|
||||
}
|
||||
}
|
||||
})
|
||||
// 浅劫持(深监视)----浅响应式
|
||||
const m2 = shallowReactive({
|
||||
name: '鸣人',
|
||||
age: 20,
|
||||
car: {
|
||||
name: '奔驰',
|
||||
color: 'red',
|
||||
city: {
|
||||
name: 'bj'
|
||||
}
|
||||
}
|
||||
})
|
||||
// 深度劫持(深监视)----深度响应式----做了reactive的处理
|
||||
const m3 = ref({
|
||||
name: '鸣人',
|
||||
age: 20,
|
||||
car: {
|
||||
name: '奔驰',
|
||||
color: 'red'
|
||||
}
|
||||
})
|
||||
// 浅劫持(浅监视)----浅响应式
|
||||
const m4 = shallowRef({
|
||||
name: '鸣人',
|
||||
age: 20,
|
||||
car: {
|
||||
name: '奔驰',
|
||||
color: 'red'
|
||||
}
|
||||
})
|
||||
|
||||
const update = () => {
|
||||
// 更改m1的数据---reactive方式
|
||||
// m1.name += '=='
|
||||
// m1.car.name += '=='
|
||||
// m1.car.city.name += '==='
|
||||
// 更改m2的数据---shallowReactive
|
||||
// m2.name += '=='
|
||||
// m2.car.name += '===' // (m2.name 和 m2.car.name 同时更新的话都会变化?神奇的呢)
|
||||
// m2.car.city.name += '==='
|
||||
// 更改m3的数据---ref方式
|
||||
// m3.value.name += '==='
|
||||
// m3.value.car.name += '==='
|
||||
// 更改m4的数据---shallowRef方式
|
||||
// m4.value.name += '==='
|
||||
// m4.value.car.name += '==='
|
||||
console.log(m3, m4)
|
||||
}
|
||||
|
||||
return {
|
||||
m1,
|
||||
m2,
|
||||
m3,
|
||||
m4,
|
||||
update
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
43
Vue/code/14.readonly和shallowReadonly/App.vue
Normal file
43
Vue/code/14.readonly和shallowReadonly/App.vue
Normal file
@@ -0,0 +1,43 @@
|
||||
<template>
|
||||
<h2>readonly和shallowReadonly</h2>
|
||||
<h3>state:{{ state2 }}</h3>
|
||||
<hr />
|
||||
<button @click="update">更新数据</button>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, reactive, readonly, shallowReadonly } from 'vue'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
setup() {
|
||||
// 深度劫持(深监视)----深度响应式
|
||||
const state = reactive({
|
||||
name: '鸣人',
|
||||
age: 20,
|
||||
car: {
|
||||
name: '奔驰',
|
||||
color: 'red'
|
||||
}
|
||||
})
|
||||
|
||||
// 只读的数据---深度的只读
|
||||
// const state2 = readonly(state)
|
||||
|
||||
// 只读的数据---浅只读的
|
||||
const state2 = shallowReadonly(state)
|
||||
const update = () => {
|
||||
// state2.name += '==='
|
||||
// state2.car.name += '=='
|
||||
|
||||
// state2.name += '==='
|
||||
state2.car.name += '=='
|
||||
}
|
||||
|
||||
return {
|
||||
state2,
|
||||
update
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
55
Vue/code/15.toRaw和markRaw/App.vue
Normal file
55
Vue/code/15.toRaw和markRaw/App.vue
Normal file
@@ -0,0 +1,55 @@
|
||||
<template>
|
||||
<h2>toRaw和markRaw</h2>
|
||||
<h3>state:{{ state }}</h3>
|
||||
<hr />
|
||||
<button @click="testToRaw">测试toRaw</button>
|
||||
<button @click="testMarkRaw">测试markRaw</button>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, markRaw, reactive, toRaw } from 'vue'
|
||||
|
||||
interface UserInfo {
|
||||
name: string
|
||||
age: number
|
||||
likes?: string[]
|
||||
}
|
||||
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
setup() {
|
||||
const state = reactive<UserInfo>({
|
||||
name: '小明',
|
||||
age: 20
|
||||
})
|
||||
|
||||
const testToRaw = () => {
|
||||
// 把代理对象变成了普通对象了,数据变化,界面不变化
|
||||
const user = toRaw(state)
|
||||
user.name += '=='
|
||||
console.log('哈哈,我好帅哦')
|
||||
}
|
||||
const testMarkRaw = () => {
|
||||
// state.likes = ['吃', '喝']
|
||||
// state.likes[0] += '=='
|
||||
// console.log(state)
|
||||
const likes = ['吃', '喝']
|
||||
// markRaw标记的对象数据,从此以后都不能再成为代理对象了
|
||||
state.likes = markRaw(likes)
|
||||
console.log(state)
|
||||
setInterval(() => {
|
||||
if (state.likes) {
|
||||
state.name += '————'
|
||||
state.likes[0] += '='
|
||||
console.log('定时器走起来')
|
||||
}
|
||||
}, 1000)
|
||||
}
|
||||
return {
|
||||
state,
|
||||
testToRaw,
|
||||
testMarkRaw
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
54
Vue/code/16_toRef的使用/App.vue
Normal file
54
Vue/code/16_toRef的使用/App.vue
Normal file
@@ -0,0 +1,54 @@
|
||||
<template>
|
||||
<h2>toRef的使用及特点:</h2>
|
||||
<h3>state:{{ state }}</h3>
|
||||
<h3>age:{{ age }}</h3>
|
||||
<h3>money:{{ money }}</h3>
|
||||
<hr />
|
||||
<button @click="update">更新数据</button>
|
||||
|
||||
<hr />
|
||||
<Child :age="age" />
|
||||
</template>
|
||||
|
||||
|
||||
<script lang="ts">
|
||||
/*
|
||||
toRef:
|
||||
为源响应式对象上的某个属性创建一个 ref对象, 二者内部操作的是同一个数据值, 更新时二者是同步的
|
||||
区别ref: 拷贝了一份新的数据值单独操作, 更新时相互不影响
|
||||
应用: 当要将某个 prop 的 ref 传递给复合函数时,toRef 很有用
|
||||
*/
|
||||
|
||||
import { defineComponent, reactive, toRef, ref } from 'vue'
|
||||
import Child from './components/Child.vue'
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
components: {
|
||||
Child
|
||||
},
|
||||
setup() {
|
||||
const state = reactive({
|
||||
age: 5,
|
||||
money: 100
|
||||
})
|
||||
// 把响应式数据state对象中的某个属性age变成了ref对象了
|
||||
const age = toRef(state, 'age')
|
||||
// 把响应式对象中的某个属性使用ref进行包装,变成了一个ref对象
|
||||
const money = ref(state.money)
|
||||
console.log(age)
|
||||
console.log(money)
|
||||
const update = () => {
|
||||
// 更新数据的
|
||||
// state.age += 2
|
||||
age.value += 3
|
||||
// money.value += 10
|
||||
}
|
||||
return {
|
||||
state,
|
||||
age,
|
||||
money,
|
||||
update
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
30
Vue/code/16_toRef的使用/components/Child.vue
Normal file
30
Vue/code/16_toRef的使用/components/Child.vue
Normal file
@@ -0,0 +1,30 @@
|
||||
<template>
|
||||
<h2>Child子级组件</h2>
|
||||
<h3>age:{{ age }}</h3>
|
||||
<h3>length:{{ length }}</h3>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, computed, Ref, toRef } from 'vue'
|
||||
|
||||
function useGetLength(age: Ref) {
|
||||
return computed(() => {
|
||||
return age.value.toString().length
|
||||
})
|
||||
}
|
||||
export default defineComponent({
|
||||
name: 'Child',
|
||||
props: {
|
||||
age: {
|
||||
type: Number,
|
||||
required: true // 必须的
|
||||
}
|
||||
},
|
||||
setup(props) {
|
||||
const length = useGetLength(toRef(props, 'age'))
|
||||
return {
|
||||
length
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
46
Vue/code/17.customRef的使用/App.vue
Normal file
46
Vue/code/17.customRef的使用/App.vue
Normal file
@@ -0,0 +1,46 @@
|
||||
<template>
|
||||
<h2>CustomRef的使用</h2>
|
||||
<input type="text" v-model="keyword" />
|
||||
<p>{{ keyword }}</p>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { customRef, defineComponent, ref } from 'vue'
|
||||
// 自定义hook防抖的函数
|
||||
// value传入的数据,将来数据的类型不确定,所以,用泛型,delay防抖的间隔时间.默认是200毫秒
|
||||
function useDebouncedRef<T>(value: T, delay = 200) {
|
||||
// 准备一个存储定时器的id的变量
|
||||
let timeOutId: number
|
||||
return customRef((track, trigger) => {
|
||||
return {
|
||||
// 返回数据的
|
||||
get() {
|
||||
// 告诉Vue追踪数据
|
||||
track()
|
||||
return value
|
||||
},
|
||||
// 设置数据的
|
||||
set(newValue: T) {
|
||||
// 清理定时器
|
||||
clearTimeout(timeOutId)
|
||||
// 开启定时器
|
||||
timeOutId = setTimeout(() => {
|
||||
value = newValue
|
||||
// 告诉Vue更新界面
|
||||
trigger()
|
||||
}, delay)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
setup() {
|
||||
// const keyword = ref('abc')
|
||||
const keyword = useDebouncedRef('abc', 500)
|
||||
return {
|
||||
keyword
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
33
Vue/code/18.provide与inject/App.vue
Normal file
33
Vue/code/18.provide与inject/App.vue
Normal file
@@ -0,0 +1,33 @@
|
||||
<template>
|
||||
<h2>provide 与 inject</h2>
|
||||
<p>当前的颜色:{{ color }}</p>
|
||||
<button @click="color = 'red'">红色</button>
|
||||
<button @click="color = 'yellow'">黄色</button>
|
||||
<button @click="color = 'green'">绿色</button>
|
||||
<hr />
|
||||
<Son />
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, provide, ref } from 'vue'
|
||||
import Son from './components/Son.vue'
|
||||
/*
|
||||
- provide` 和 `inject` 提供依赖注入,功能类似 2.x 的 `provide/inject
|
||||
- 实现跨层级组件(祖孙)间通信
|
||||
*/
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
components: {
|
||||
Son
|
||||
},
|
||||
setup() {
|
||||
// 响应式的数据
|
||||
const color = ref('red')
|
||||
// 提供数据
|
||||
provide('color', color)
|
||||
return {
|
||||
color
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
18
Vue/code/18.provide与inject/components/GrandSon.vue
Normal file
18
Vue/code/18.provide与inject/components/GrandSon.vue
Normal file
@@ -0,0 +1,18 @@
|
||||
<template>
|
||||
<h3 :style="{ color }">GrandSon孙子组件</h3>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, inject } from 'vue'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'GrandSon',
|
||||
setup() {
|
||||
// 注入的操作
|
||||
const color = inject('color')
|
||||
return {
|
||||
color
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
17
Vue/code/18.provide与inject/components/Son.vue
Normal file
17
Vue/code/18.provide与inject/components/Son.vue
Normal file
@@ -0,0 +1,17 @@
|
||||
<template>
|
||||
<h3>Son子级组件</h3>
|
||||
<hr />
|
||||
<GrandSon />
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent } from 'vue'
|
||||
import GrandSon from './GrandSon.vue'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'Son',
|
||||
components: {
|
||||
GrandSon
|
||||
}
|
||||
})
|
||||
</script>
|
||||
29
Vue/code/19.响应式数据判断的相关方法/App.vue
Normal file
29
Vue/code/19.响应式数据判断的相关方法/App.vue
Normal file
@@ -0,0 +1,29 @@
|
||||
<template>
|
||||
<h2>响应式数据的判断</h2>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, isProxy, isReactive, isReadonly, isRef, reactive, readonly, ref } from 'vue'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
// isRef: 检查一个值是否为一个 ref 对象
|
||||
// isReactive: 检查一个对象是否是由 reactive 创建的响应式代理
|
||||
// isReadonly: 检查一个对象是否是由 readonly 创建的只读代理
|
||||
// isProxy: 检查一个对象是否是由 reactive 或者 readonly 方法创建的代理
|
||||
|
||||
setup() {
|
||||
// isRef: 检查一个值是否为一个 ref 对象
|
||||
console.log(isRef(ref({})))
|
||||
// isReactive: 检查一个对象是否是由 reactive 创建的响应式代理
|
||||
console.log(isReactive(reactive({})))
|
||||
// isReadonly: 检查一个对象是否是由 readonly 创建的只读代理
|
||||
console.log(isReadonly(readonly({})))
|
||||
// isProxy: 检查一个对象是否是由 reactive 或者 readonly 方法创建的代理
|
||||
console.log(isProxy(readonly({})))
|
||||
console.log(isProxy(reactive({})))
|
||||
|
||||
return {}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
110
Vue/code/20.手写组合API/index.html
Normal file
110
Vue/code/20.手写组合API/index.html
Normal file
@@ -0,0 +1,110 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>20.手写组合API</title>
|
||||
</head>
|
||||
<body>
|
||||
<script src="./index.js"></script>
|
||||
<script type="text/javascript">
|
||||
// ==========================
|
||||
// !todo 测试shallowReactive和reactive
|
||||
const proxyUser1 = shallowReactive({
|
||||
name: '小明',
|
||||
car: {
|
||||
color: 'red'
|
||||
}
|
||||
})
|
||||
// // 拦截到了读和写的数据
|
||||
// proxyUser1.name += '=='
|
||||
// // 拦截到了读取数据,但是拦截不到写的数据
|
||||
// proxyUser1.car.color + '=='
|
||||
// // 拦截到了删除数据
|
||||
// delete proxyUser1.name
|
||||
// // 只拦截到了读,但是拦截不到删除
|
||||
// delete proxyUser1.car.color
|
||||
|
||||
const proxyUser2 = reactive({
|
||||
name: '小明',
|
||||
car: {
|
||||
color: 'red'
|
||||
}
|
||||
})
|
||||
// 拦截到了读和修改的数据
|
||||
// proxyUser2.name += '=='
|
||||
// // 拦截到了读和修改的数据
|
||||
// proxyUser2.car.color = '=='
|
||||
// // 拦截了删除
|
||||
// delete proxyUser2.name
|
||||
// // 拦截到了读和拦截到了删除
|
||||
// delete proxyUser2.car.color
|
||||
|
||||
// ==========================
|
||||
// !todo 测试shallowReadonly和readonly
|
||||
const proxyUser3 = shallowReadonly({
|
||||
name: '小明',
|
||||
cars: ['奔驰', '宝马']
|
||||
})
|
||||
// // 可以读取
|
||||
// console.log(proxyUser3.name)
|
||||
// // 不能修改
|
||||
// proxyUser3.name = '=='
|
||||
// // 不能删除
|
||||
// delete proxyUser3.name
|
||||
// // 拦截到了读取,可以修改
|
||||
// proxyUser3.cars[0] = '奥迪'
|
||||
// // 拦截到了读取,可以删除
|
||||
// delete proxyUser3.cars[0]
|
||||
// console.log(proxyUser3)
|
||||
|
||||
const proxyUser4 = readonly({
|
||||
name: '小明',
|
||||
cars: ['奔驰', '宝马']
|
||||
})
|
||||
// // 可以读取
|
||||
// console.log(proxyUser4.name)
|
||||
// // 不能修改
|
||||
// proxyUser4.name = '=='
|
||||
// // 不能删除
|
||||
// delete proxyUser4.name
|
||||
// // 拦截到了读取,不可以修改
|
||||
// proxyUser4.cars[0] = '奥迪'
|
||||
// // 拦截到了读取,不可以删除
|
||||
// delete proxyUser4.cars[0]
|
||||
// console.log(proxyUser4)
|
||||
|
||||
// ==========================
|
||||
// !todo 测试 shallowRef 和 ref
|
||||
const proxyUser5 = shallowRef({
|
||||
name: '小明',
|
||||
cars: {
|
||||
color: 'red'
|
||||
}
|
||||
})
|
||||
// console.log(proxyUser5.value)
|
||||
// // 劫持到
|
||||
// proxyUser5.value = '=='
|
||||
// // 劫持不到
|
||||
// proxyUser5.value.car = '=='
|
||||
|
||||
const proxyUser6 = ref({
|
||||
name: '小明',
|
||||
cars: {
|
||||
color: 'red'
|
||||
}
|
||||
})
|
||||
// console.log(proxyUser6.value)
|
||||
// // // 劫持到
|
||||
// // proxyUser6.value = '=='
|
||||
// // 劫持到
|
||||
// proxyUser6.value.car = '=='
|
||||
|
||||
console.log(isRef(ref({})))
|
||||
console.log(isReactive(reactive({})))
|
||||
console.log(isReadonly(readonly({})))
|
||||
console.log(isProxy(reactive({})))
|
||||
console.log(isProxy(readonly({})))
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
165
Vue/code/20.手写组合API/index.js
Normal file
165
Vue/code/20.手写组合API/index.js
Normal file
@@ -0,0 +1,165 @@
|
||||
// shallowReactive(浅的劫持,浅的监视,浅的响应数据) 与 reactive(深的)
|
||||
|
||||
// TODO 68_尚硅谷_Vue3-手写shallowReactive和reactive
|
||||
// 定义一个reactiveHandler处理对象
|
||||
const reactiveHandler = {
|
||||
// 获取属性值
|
||||
get(target, prop) {
|
||||
if (prop === '_is_reactive') return true
|
||||
const result = Reflect.get(target, prop)
|
||||
console.log('拦截了读取数据', prop, result)
|
||||
return result
|
||||
},
|
||||
// 修改属性值或者是添加属性
|
||||
set(target, prop, value) {
|
||||
const result = Reflect.set(target, prop, value)
|
||||
console.log('拦截了修改数据或者是添加属性', prop, value)
|
||||
return result
|
||||
},
|
||||
// 删除某个属性
|
||||
deleteProperty(target, prop) {
|
||||
const result = Reflect.deleteProperty(target, prop)
|
||||
console.log('拦截了删除数据', prop)
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
// 定义一个shallowReactive函数,传入一个目标对象
|
||||
function shallowReactive(target) {
|
||||
// 判断当前的目标对象是不是object类型(对象/数组)
|
||||
if (target && typeof target === 'object') {
|
||||
return new Proxy(target, reactiveHandler)
|
||||
}
|
||||
// 如果传入的数据是基本类型的数据,那么就直接返回
|
||||
return target
|
||||
}
|
||||
|
||||
// 定义一个reactive函数,传入一个目标对象
|
||||
function reactive(target) {
|
||||
// 判断当前的目标对象是不是object类型(对象/数组)
|
||||
if (target && typeof target === 'object') {
|
||||
// 对数组或者是对象中所有的数据进行reactive的递归处理
|
||||
// 先判断当前的数据是不是数组
|
||||
if (Array.isArray(target)) {
|
||||
// 数组的数据要进行遍历操作
|
||||
target.forEach((item, index) => {
|
||||
target[index] = reactive(item)
|
||||
})
|
||||
} else {
|
||||
// 再判断当前的数据是不是对象
|
||||
// 对象的数据也要进行遍历的操作
|
||||
Object.keys(target).forEach(key => {
|
||||
target[key] = reactive(target[key])
|
||||
})
|
||||
}
|
||||
return new Proxy(target, reactiveHandler)
|
||||
}
|
||||
// 如果传入的数据是基本类型的数据,那么就直接返回
|
||||
return target
|
||||
}
|
||||
|
||||
// TODO 69_尚硅谷_Vue3-手写shallowReadonly和readonly
|
||||
// 定义了一个readonlyHandler处理器
|
||||
const readonlyHandler = {
|
||||
get(target, prop) {
|
||||
if (prop === '_is_readonly') return true
|
||||
const result = Reflect.get(target, prop)
|
||||
console.log('拦截到了读取数据了', prop, result)
|
||||
return result
|
||||
},
|
||||
set(target, prop, value) {
|
||||
console.warn('只能读取数据,不能修改数据或者添加数据')
|
||||
return true
|
||||
},
|
||||
deleteProperty(target, prop) {
|
||||
console.warn('只能读取数据,不能删除数据')
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// 定义一个shallowReadonly函数
|
||||
function shallowReadonly(target) {
|
||||
// 需要判断当前的数据是不是对象
|
||||
if (target && typeof target === 'object') {
|
||||
return new Proxy(target, readonlyHandler)
|
||||
}
|
||||
return target
|
||||
}
|
||||
|
||||
// 定义一个readonly函数
|
||||
function readonly(target) {
|
||||
// 需要判断当前的数据是不是对象
|
||||
if (target && typeof target === 'object') {
|
||||
// 判断target是不是数组
|
||||
if (Array.isArray(target)) {
|
||||
// 遍历数组
|
||||
target.forEach((item, index) => {
|
||||
target[index] = readonly(item)
|
||||
})
|
||||
} else {
|
||||
// 判断target是不是对象
|
||||
// 遍历对象
|
||||
Object.keys(target).forEach(key => {
|
||||
target[key] = readonly(target[key])
|
||||
})
|
||||
}
|
||||
return new Proxy(target, readonlyHandler)
|
||||
}
|
||||
// 如果不是对象或者数组,那么直接返回
|
||||
return target
|
||||
}
|
||||
|
||||
// TODO 70_尚硅谷_Vue3-手写 shallowRef 和 ref
|
||||
|
||||
// 定义一个shallowRef函数
|
||||
function shallowRef(target) {
|
||||
return {
|
||||
// 保存target数据保存起来
|
||||
_value: target,
|
||||
get value() {
|
||||
console.log('劫持到了读取数据')
|
||||
return this._value
|
||||
},
|
||||
set value(val) {
|
||||
console.log('劫持到了修改数据,准备更新界面', val)
|
||||
this._value = val
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 定义一个ref函数
|
||||
function ref(target) {
|
||||
target = reactive(target)
|
||||
return {
|
||||
_is_ref: true, // 标识当前的对象是ref对象
|
||||
// 保存target数据保存起来
|
||||
_value: target,
|
||||
get value() {
|
||||
console.log('劫持到了读取数据')
|
||||
return this._value
|
||||
},
|
||||
set value(val) {
|
||||
console.log('劫持到了修改数据,准备更新界面', val)
|
||||
this._value = val
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO 71_尚硅谷_Vue3-手写isRef和isReactive和isReadonly
|
||||
|
||||
// 定义一个函数isRef,判断当前的对象是不是ref对象
|
||||
function isRef(obj) {
|
||||
return obj && obj._is_ref
|
||||
}
|
||||
// 定义一个函数isReactive,判断当前的对象是不是reactive对象
|
||||
function isReactive(obj) {
|
||||
return obj && obj._is_reactive
|
||||
}
|
||||
// 定义一个函数isReadonly,判断当前的对象是不是readonly对象
|
||||
function isReadonly(obj) {
|
||||
return obj && obj._is_readonly
|
||||
}
|
||||
// 定义一个函数isProxy,判断当前的对象是不是reactive对象或者readonly对象
|
||||
function isProxy(obj) {
|
||||
return isReactive(obj) || isReadonly(obj)
|
||||
}
|
||||
21
Vue/code/21.Fragment组件的介绍/App.vue
Normal file
21
Vue/code/21.Fragment组件的介绍/App.vue
Normal file
@@ -0,0 +1,21 @@
|
||||
<template>
|
||||
<!--根标签-->
|
||||
<!-- <div>
|
||||
<h2>测试1</h2>
|
||||
<h2>测试2</h2>
|
||||
</div> -->
|
||||
|
||||
<!--
|
||||
在Vue3中: 组件可以没有根标签, 内部会将多个标签包含在一个Fragment虚拟元素中
|
||||
好处: 减少标签层级, 减小内存占用
|
||||
-->
|
||||
<h2>测试1</h2>
|
||||
<h2>测试2</h2>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent } from 'vue'
|
||||
export default defineComponent({
|
||||
name: 'App'
|
||||
})
|
||||
</script>
|
||||
17
Vue/code/22.Teleport组件介绍/App.vue
Normal file
17
Vue/code/22.Teleport组件介绍/App.vue
Normal file
@@ -0,0 +1,17 @@
|
||||
<template>
|
||||
<h2>App父级组件</h2>
|
||||
<hr />
|
||||
<ModalButton />
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent } from 'vue'
|
||||
import ModalButton from './ModalButton.vue'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
components: {
|
||||
ModalButton
|
||||
}
|
||||
})
|
||||
</script>
|
||||
55
Vue/code/22.Teleport组件介绍/ModalButton.vue
Normal file
55
Vue/code/22.Teleport组件介绍/ModalButton.vue
Normal file
@@ -0,0 +1,55 @@
|
||||
<template>
|
||||
<button @click="modalOpen = true">打开一个对话框</button>
|
||||
|
||||
<Teleport to="body">
|
||||
<div v-if="modalOpen" class="modal">
|
||||
<div>
|
||||
这是对话框
|
||||
<button @click="modalOpen = false">关闭对话框</button>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, ref } from 'vue'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'ModalButton',
|
||||
setup() {
|
||||
// 控制对话框显示或者隐藏的
|
||||
const modalOpen = ref(false)
|
||||
return {
|
||||
modalOpen
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
<style>
|
||||
.modal {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
background-color: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.modal div {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background-color: white;
|
||||
width: 300px;
|
||||
height: 300px;
|
||||
padding: 5px;
|
||||
}
|
||||
</style>
|
||||
36
Vue/code/23.Suspense组件的使用/App.vue
Normal file
36
Vue/code/23.Suspense组件的使用/App.vue
Normal file
@@ -0,0 +1,36 @@
|
||||
<template>
|
||||
<h2>App父级组件:Suspense组件的使用</h2>
|
||||
|
||||
<Suspense>
|
||||
<template #default>
|
||||
<!--异步组件-->
|
||||
<!-- <AsyncComponent /> -->
|
||||
<AsyncAddress />
|
||||
</template>
|
||||
<template v-slot:fallback>
|
||||
<!--loading的内容-->
|
||||
<h2>Loading.....</h2>
|
||||
</template>
|
||||
</Suspense>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, defineAsyncComponent } from 'vue'
|
||||
|
||||
// 引入组件:静态引入和动态引入
|
||||
// Vue2中的动态引入组件的写法:(在Vue3中这种写法不行)
|
||||
// const AsyncComponent = () => import('./AsyncComponent.vue')
|
||||
// Vue3中的动态引入组件的写法
|
||||
// const AsyncComponent = defineAsyncComponent(() => import('./AsyncComponent.vue'))
|
||||
|
||||
// 静态引入组件
|
||||
// import AsyncComponent from './AsyncComponent.vue'
|
||||
import AsyncAddress from './AsyncAddress.vue'
|
||||
export default defineComponent({
|
||||
name: 'App',
|
||||
components: {
|
||||
// AsyncComponent,
|
||||
AsyncAddress
|
||||
}
|
||||
})
|
||||
</script>
|
||||
27
Vue/code/23.Suspense组件的使用/AsyncAddress.vue
Normal file
27
Vue/code/23.Suspense组件的使用/AsyncAddress.vue
Normal file
@@ -0,0 +1,27 @@
|
||||
<template>
|
||||
<h2>AsyncAddress组件</h2>
|
||||
<h3>{{ data }}</h3>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent } from 'vue'
|
||||
import axios from 'axios'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'AsyncAddress',
|
||||
// setup() {
|
||||
// return axios.get('/data/address.json').then((response) => {
|
||||
// return {
|
||||
// data: response.data
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
async setup() {
|
||||
const result = await axios.get('/data/address.json')
|
||||
return {
|
||||
data: result.data
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
22
Vue/code/23.Suspense组件的使用/AsyncComponent.vue
Normal file
22
Vue/code/23.Suspense组件的使用/AsyncComponent.vue
Normal file
@@ -0,0 +1,22 @@
|
||||
<template>
|
||||
<h2>AsyncComponent子级组件</h2>
|
||||
<h3>{{ msg }}</h3>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent } from 'vue'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'AsyncComponent',
|
||||
setup() {
|
||||
return new Promise((resolve, reject) => {
|
||||
setTimeout(() => {
|
||||
resolve({
|
||||
msg: 'what are you no sha lei'
|
||||
})
|
||||
}, 2000)
|
||||
})
|
||||
// return {}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
30
Vue/code/vue-project/.gitignore
vendored
Normal file
30
Vue/code/vue-project/.gitignore
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
.DS_Store
|
||||
dist
|
||||
dist-ssr
|
||||
coverage
|
||||
*.local
|
||||
|
||||
/cypress/videos/
|
||||
/cypress/screenshots/
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
*.tsbuildinfo
|
||||
40
Vue/code/vue-project/README.md
Normal file
40
Vue/code/vue-project/README.md
Normal file
@@ -0,0 +1,40 @@
|
||||
# vue-project
|
||||
|
||||
This template should help get you started developing with Vue 3 in Vite.
|
||||
|
||||
## Recommended IDE Setup
|
||||
|
||||
[VSCode](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur) + [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin).
|
||||
|
||||
## Type Support for `.vue` Imports in TS
|
||||
|
||||
TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin) to make the TypeScript language service aware of `.vue` types.
|
||||
|
||||
If the standalone TypeScript plugin doesn't feel fast enough to you, Volar has also implemented a [Take Over Mode](https://github.com/johnsoncodehk/volar/discussions/471#discussioncomment-1361669) that is more performant. You can enable it by the following steps:
|
||||
|
||||
1. Disable the built-in TypeScript Extension
|
||||
1) Run `Extensions: Show Built-in Extensions` from VSCode's command palette
|
||||
2) Find `TypeScript and JavaScript Language Features`, right click and select `Disable (Workspace)`
|
||||
2. Reload the VSCode window by running `Developer: Reload Window` from the command palette.
|
||||
|
||||
## Customize configuration
|
||||
|
||||
See [Vite Configuration Reference](https://vitejs.dev/config/).
|
||||
|
||||
## Project Setup
|
||||
|
||||
```sh
|
||||
npm install
|
||||
```
|
||||
|
||||
### Compile and Hot-Reload for Development
|
||||
|
||||
```sh
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### Type-Check, Compile and Minify for Production
|
||||
|
||||
```sh
|
||||
npm run build
|
||||
```
|
||||
1
Vue/code/vue-project/env.d.ts
vendored
Normal file
1
Vue/code/vue-project/env.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
13
Vue/code/vue-project/index.html
Normal file
13
Vue/code/vue-project/index.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Vite App</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
26
Vue/code/vue-project/package.json
Normal file
26
Vue/code/vue-project/package.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "vue-project",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "run-p type-check \"build-only {@}\" --",
|
||||
"preview": "vite preview",
|
||||
"build-only": "vite build",
|
||||
"type-check": "vue-tsc --build --force"
|
||||
},
|
||||
"dependencies": {
|
||||
"vue": "^3.3.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tsconfig/node18": "^18.2.2",
|
||||
"@types/node": "^18.19.3",
|
||||
"@vitejs/plugin-vue": "^4.5.2",
|
||||
"@vue/tsconfig": "^0.5.0",
|
||||
"npm-run-all2": "^6.1.1",
|
||||
"typescript": "~5.3.0",
|
||||
"vite": "^5.0.10",
|
||||
"vue-tsc": "^1.8.25"
|
||||
}
|
||||
}
|
||||
24
Vue/code/vue-project/src/App.vue
Normal file
24
Vue/code/vue-project/src/App.vue
Normal file
@@ -0,0 +1,24 @@
|
||||
<template>
|
||||
<div class="app">
|
||||
<h1>Hello Vue!</h1>
|
||||
<Person />
|
||||
</div>
|
||||
|
||||
|
||||
<main>
|
||||
<TheWelcome />
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import Person from './components/Person.vue'
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.app {
|
||||
background-color: #ddd;
|
||||
box-shadow: 0 0 10px;
|
||||
border-radius: 10px;
|
||||
padding: 10px;
|
||||
}
|
||||
</style>
|
||||
132
Vue/code/vue-project/src/components/Person.vue
Normal file
132
Vue/code/vue-project/src/components/Person.vue
Normal file
@@ -0,0 +1,132 @@
|
||||
|
||||
<template>
|
||||
<div class="person">
|
||||
<h2>知识点1:ref/reactive支持</h2>
|
||||
<h3>姓名:{{ person.name }}</h3>
|
||||
<h3>年龄:{{ person.age }}</h3>
|
||||
<button @click="changeNameToRef">改变姓名</button>
|
||||
<button @click="changeAgeToRef">改变年龄</button>
|
||||
<button @click="changeNameAndAge">改变人物</button>
|
||||
|
||||
<h2>知识点2:computed 计算属性</h2>
|
||||
<h3>姓名:<input type="text" v-model="person.name" /> </h3>
|
||||
<h3>年龄:<input type="text" v-model="person.age" /> </h3>
|
||||
<h3>姓名-年龄:{{ nameAge }}</h3>
|
||||
|
||||
|
||||
<h2>知识点3:watch 监控变化</h2>
|
||||
<h2>reactiveVal:{{reactiveVal.a.b.c}}</h2>
|
||||
<button @click="changeReactiveVal">修改变量</button>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
<!-- -->
|
||||
<script lang="ts" setup >
|
||||
// js与java一样,所有的变量都是指针,你可以修改指针绑定的地址然后指向其他对象,也可以修改指针指向的对象的内容,不会改变地址值。
|
||||
//如果你修改指针本身,让变量指向了另一个对象,指针相当于该表。
|
||||
//const对象的地址不能修改,即你不能修改指针已经绑定的地址,不能修改指向其他对象
|
||||
//let对象的地址是能修改的,你能修改指针绑定的地址。即修改指向其他对象
|
||||
|
||||
//reactive的局限性。重新分配创建指向响应式数据对象是没有意义的。原有的响应式数据对象已经绑定到template中的数据,新创建的响应式数据对象并不会绑定到template中的数据。
|
||||
// 由于reactive没有像ref一样重新包装一层,其直接指向响应式数据,所以你无法直接更新reactive绑定的指针地址,只能修改其指向的对象。
|
||||
// 因为你一旦修改绑定的地址,就相当于指向了一个新的对象,而原来的响应式数据对象就丢失了,你新建的响应式数据并没有被vue接管,也无法被接管。
|
||||
// ref变量同理,你也无法直接修改ref变量绑定新的指针地址,这会导致原来的响应式数据对象丢失,无法实现响应式的过程
|
||||
// 但就巧妙在ref是在原对象外包装了一层,你直接修改其.value指向的对象,并不会修改ref变量指向的对象,所以能更好的应对各种情况。
|
||||
import { ref, reactive, computed, watch, toRefs } from 'vue'
|
||||
let person = ref({
|
||||
name: '张三',
|
||||
age: 18
|
||||
})
|
||||
|
||||
//ToRefs toRef能够结构赋值
|
||||
const { name, age } = toRefs(person.value)
|
||||
function changeNameToRef() {
|
||||
name.value += '~'
|
||||
}
|
||||
|
||||
function changeAgeToRef() {
|
||||
age.value += 1
|
||||
}
|
||||
|
||||
// 不修改指针绑定的地址,修改指向的对象的内容
|
||||
const changeName = () => {
|
||||
person.value.name += '~'
|
||||
}
|
||||
|
||||
// 不修改指针绑定的地址,修改指向的对象的内容
|
||||
const changeAge = () => {
|
||||
person.value.age += 1
|
||||
}
|
||||
|
||||
// 修改指针绑定的地址,指向其他对象。
|
||||
function changeNameAndAge(){
|
||||
person.value = {name: "李四",age:99}
|
||||
}
|
||||
|
||||
const nameAge = computed(() => {
|
||||
return person.value.name + '-' + person.value.age
|
||||
})
|
||||
|
||||
|
||||
// 满足条件后停止监视,deep能够监视内部数据的变化
|
||||
// watch也只能监视响应式对象数据内容的变化,而不是地址的变化。如果创建一个新的对象或赋予新的地址都监视不到。
|
||||
const stopWatch = watch(person, (newVal, oldVal) => {
|
||||
console.log("watched:",newVal,oldVal);
|
||||
// stopWatch();
|
||||
},{deep:true})
|
||||
|
||||
|
||||
let reactiveVal = reactive({
|
||||
a:{
|
||||
b:{
|
||||
c:123
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
function changeReactiveVal(){
|
||||
reactiveVal.a.b.c = 456;
|
||||
}
|
||||
//当监视的是reactive对象的时候,默认开启深度监视,并且无法关闭
|
||||
watch(reactiveVal,(newVal,oldVal)=>{
|
||||
console.log("watched",newVal,oldVal)
|
||||
})
|
||||
|
||||
// 可以通过函数监视某个其中的属性,通过监视一个函数返回值的地址值是否发生变化来决定是否执行回到函数
|
||||
watch(() => reactiveVal.a.b.c,(newVal,oldVal)=>{
|
||||
console.log("watched",newVal,oldVal)
|
||||
})
|
||||
import {watchEffect,defineExpose} from 'vue'
|
||||
//快速监视,不需要声明监视什么变量,自动监视
|
||||
watchEffect(()=>{
|
||||
reactiveVal.a.b.c = 1999
|
||||
})
|
||||
|
||||
//导出一些对象,当前的组件实例
|
||||
defineExpose({reactiveVal})
|
||||
|
||||
|
||||
//接收外部变量
|
||||
let x = defineProps(['a'])
|
||||
|
||||
// 接收list+限制类型+必要值+默认值
|
||||
import {withDefaults} from 'vue'
|
||||
withDefaults(defineProps<{list?:string}>(),{
|
||||
list:()=>'a'
|
||||
})
|
||||
|
||||
</script>
|
||||
|
||||
|
||||
<style scoped>
|
||||
.person {
|
||||
background-color: skyblue;
|
||||
box-shadow: 0 0 10px;
|
||||
border-radius: 10px;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
button {
|
||||
margin: 5px;
|
||||
}
|
||||
</style>
|
||||
5
Vue/code/vue-project/src/main.ts
Normal file
5
Vue/code/vue-project/src/main.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
|
||||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
|
||||
createApp(App).mount('#app')
|
||||
13
Vue/code/vue-project/tsconfig.app.json
Normal file
13
Vue/code/vue-project/tsconfig.app.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "@vue/tsconfig/tsconfig.dom.json",
|
||||
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
|
||||
"exclude": ["src/**/__tests__/*"],
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"noEmit": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
11
Vue/code/vue-project/tsconfig.json
Normal file
11
Vue/code/vue-project/tsconfig.json
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.node.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.app.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
17
Vue/code/vue-project/tsconfig.node.json
Normal file
17
Vue/code/vue-project/tsconfig.node.json
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"extends": "@tsconfig/node18/tsconfig.json",
|
||||
"include": [
|
||||
"vite.config.*",
|
||||
"vitest.config.*",
|
||||
"cypress.config.*",
|
||||
"nightwatch.conf.*",
|
||||
"playwright.config.*"
|
||||
],
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"noEmit": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"types": ["node"]
|
||||
}
|
||||
}
|
||||
16
Vue/code/vue-project/vite.config.ts
Normal file
16
Vue/code/vue-project/vite.config.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
vue(),
|
||||
],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url))
|
||||
}
|
||||
}
|
||||
})
|
||||
616
Vue/vue3/vue3快速上手.md
Normal file
616
Vue/vue3/vue3快速上手.md
Normal file
@@ -0,0 +1,616 @@
|
||||
# Vue3快速上手
|
||||
|
||||
|
||||
## 1.Vue3带来了什么
|
||||
|
||||
### 1.性能的提升
|
||||
|
||||
- 打包大小减少41%
|
||||
|
||||
- 初次渲染快55%, 更新渲染快133%
|
||||
|
||||
- 内存减少54%
|
||||
|
||||
......
|
||||
|
||||
### 2.源码的升级
|
||||
|
||||
- 使用Proxy代替defineProperty实现响应式
|
||||
|
||||
- 重写虚拟DOM的实现和Tree-Shaking
|
||||
|
||||
......
|
||||
|
||||
### 3.拥抱TypeScript
|
||||
|
||||
- Vue3可以更好的支持TypeScript
|
||||
|
||||
### 4.新的特性
|
||||
|
||||
1. Composition API(组合API)
|
||||
|
||||
- setup配置
|
||||
- ref与reactive
|
||||
- watch与watchEffect
|
||||
- provide与inject
|
||||
- ......
|
||||
2. 新的内置组件
|
||||
- Fragment
|
||||
- Teleport
|
||||
- Suspense
|
||||
3. 其他改变
|
||||
|
||||
- 新的生命周期钩子
|
||||
- data 选项应始终被声明为一个函数
|
||||
- 移除keyCode支持作为 v-on 的修饰符
|
||||
- ......
|
||||
|
||||
# 一、创建Vue3.0工程
|
||||
|
||||
## 1.使用 vue-cli 创建
|
||||
|
||||
官方文档:https://cli.vuejs.org/zh/guide/creating-a-project.html#vue-create
|
||||
|
||||
```bash
|
||||
## 查看@vue/cli版本,确保@vue/cli版本在4.5.0以上
|
||||
vue --version
|
||||
## 安装或者升级你的@vue/cli
|
||||
npm install -g @vue/cli
|
||||
## 创建
|
||||
vue create vue_test
|
||||
## 启动
|
||||
cd vue_test
|
||||
npm run serve
|
||||
```
|
||||
|
||||
## 2.使用 vite 创建
|
||||
|
||||
官方文档:https://v3.cn.vuejs.org/guide/installation.html#vite
|
||||
|
||||
vite官网:https://vitejs.cn
|
||||
|
||||
- 什么是vite?—— 新一代前端构建工具。
|
||||
- 优势如下:
|
||||
- 开发环境中,无需打包操作,可快速的冷启动。
|
||||
- 轻量快速的热重载(HMR)。
|
||||
- 真正的按需编译,不再等待整个应用编译完成。
|
||||
- 传统构建 与 vite构建对比图
|
||||
|
||||
|
||||
```bash
|
||||
## 创建工程
|
||||
npm init vite-app <project-name>
|
||||
## 进入工程目录
|
||||
cd <project-name>
|
||||
## 安装依赖
|
||||
npm install
|
||||
## 运行
|
||||
npm run dev
|
||||
```
|
||||
|
||||
# 二、常用 Composition API
|
||||
|
||||
官方文档: https://v3.cn.vuejs.org/guide/composition-api-introduction.html
|
||||
|
||||
## 1.拉开序幕的setup
|
||||
|
||||
1. 理解:Vue3.0中一个新的配置项,值为一个函数。
|
||||
2. setup是所有<strong style="color:#DD5145">Composition API(组合API)</strong><i style="color:gray;font-weight:bold">“ 表演的舞台 ”</i>。
|
||||
4. 组件中所用到的:数据、方法等等,均要配置在setup中。
|
||||
5. setup函数的两种返回值:
|
||||
1. 若返回一个对象,则对象中的属性、方法, 在模板中均可以直接使用。(重点关注!)
|
||||
2. <span style="color:#aad">若返回一个渲染函数:则可以自定义渲染内容。(了解)</span>
|
||||
6. 注意点:
|
||||
1. 尽量不要与Vue2.x配置混用
|
||||
- Vue2.x配置(data、methos、computed...)中<strong style="color:#DD5145">可以访问到</strong>setup中的属性、方法。
|
||||
- 但在setup中<strong style="color:#DD5145">不能访问到</strong>Vue2.x配置(data、methos、computed...)。
|
||||
- 如果有重名, setup优先。
|
||||
2. setup不能是一个async函数,因为返回值不再是return的对象, 而是promise, 模板看不到return对象中的属性。(后期也可以返回一个Promise实例,但需要Suspense和异步组件的配合)
|
||||
|
||||
## 2.ref函数
|
||||
|
||||
- 作用: 定义一个响应式的数据
|
||||
- 语法: ```const xxx = ref(initValue)```
|
||||
- 创建一个包含响应式数据的<strong style="color:#DD5145">引用对象(reference对象,简称ref对象)</strong>。
|
||||
- JS中操作数据: ```xxx.value```
|
||||
- 模板中读取数据: 不需要.value,直接:```<div>{{xxx}}</div>```
|
||||
- 备注:
|
||||
- 接收的数据可以是:基本类型、也可以是对象类型。
|
||||
- 基本类型的数据:响应式依然是靠``Object.defineProperty()``的```get```与```set```完成的。
|
||||
- 对象类型的数据:内部 <i style="color:gray;font-weight:bold">“ 求助 ”</i> 了Vue3.0中的一个新函数—— ```reactive```函数。
|
||||
|
||||
## 3.reactive函数
|
||||
|
||||
- 作用: 定义一个<strong style="color:#DD5145">对象类型</strong>的响应式数据(基本类型不要用它,要用```ref```函数)
|
||||
- 语法:```const 代理对象= reactive(源对象)```接收一个对象(或数组),返回一个<strong style="color:#DD5145">代理对象(Proxy的实例对象,简称proxy对象)</strong>
|
||||
- reactive定义的响应式数据是“深层次的”。
|
||||
- 内部基于 ES6 的 Proxy 实现,通过代理对象操作源对象内部数据进行操作。
|
||||
|
||||
## 4.Vue3.0中的响应式原理
|
||||
|
||||
### vue2.x的响应式
|
||||
|
||||
- 实现原理:
|
||||
- 对象类型:通过```Object.defineProperty()```对属性的读取、修改进行拦截(数据劫持)。
|
||||
|
||||
- 数组类型:通过重写更新数组的一系列方法来实现拦截。(对数组的变更方法进行了包裹)。
|
||||
|
||||
```js
|
||||
Object.defineProperty(data, 'count', {
|
||||
get () {},
|
||||
set () {}
|
||||
})
|
||||
```
|
||||
|
||||
- 存在问题:
|
||||
- 新增属性、删除属性, 界面不会更新。
|
||||
- 直接通过下标修改数组, 界面不会自动更新。
|
||||
|
||||
### Vue3.0的响应式
|
||||
|
||||
- 实现原理:
|
||||
- 通过Proxy(代理): 拦截对象中任意属性的变化, 包括:属性值的读写、属性的添加、属性的删除等。
|
||||
- 通过Reflect(反射): 对源对象的属性进行操作。
|
||||
- MDN文档中描述的Proxy与Reflect:
|
||||
- Proxy:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy
|
||||
|
||||
- Reflect:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Reflect
|
||||
|
||||
```js
|
||||
new Proxy(data, {
|
||||
// 拦截读取属性值
|
||||
get (target, prop) {
|
||||
return Reflect.get(target, prop)
|
||||
},
|
||||
// 拦截设置属性值或添加新属性
|
||||
set (target, prop, value) {
|
||||
return Reflect.set(target, prop, value)
|
||||
},
|
||||
// 拦截删除属性
|
||||
deleteProperty (target, prop) {
|
||||
return Reflect.deleteProperty(target, prop)
|
||||
}
|
||||
})
|
||||
|
||||
proxy.name = 'tom'
|
||||
```
|
||||
|
||||
## 5.reactive对比ref
|
||||
|
||||
- 从定义数据角度对比:
|
||||
- ref用来定义:<strong style="color:#DD5145">基本类型数据</strong>。
|
||||
- reactive用来定义:<strong style="color:#DD5145">对象(或数组)类型数据</strong>。
|
||||
- 备注:ref也可以用来定义<strong style="color:#DD5145">对象(或数组)类型数据</strong>, 它内部会自动通过```reactive```转为<strong style="color:#DD5145">代理对象</strong>。
|
||||
- 从原理角度对比:
|
||||
- ref通过``Object.defineProperty()``的```get```与```set```来实现响应式(数据劫持)。
|
||||
- reactive通过使用<strong style="color:#DD5145">Proxy</strong>来实现响应式(数据劫持), 并通过<strong style="color:#DD5145">Reflect</strong>操作<strong style="color:orange">源对象</strong>内部的数据。
|
||||
- 从使用角度对比:
|
||||
- ref定义的数据:操作数据<strong style="color:#DD5145">需要</strong>```.value```,读取数据时模板中直接读取<strong style="color:#DD5145">不需要</strong>```.value```。
|
||||
- reactive定义的数据:操作数据与读取数据:<strong style="color:#DD5145">均不需要</strong>```.value```。
|
||||
|
||||
## 6.setup的两个注意点
|
||||
|
||||
- setup执行的时机
|
||||
- 在beforeCreate之前执行一次,this是undefined。
|
||||
|
||||
- setup的参数
|
||||
- props:值为对象,包含:组件外部传递过来,且组件内部声明接收了的属性。
|
||||
- context:上下文对象
|
||||
- attrs: 值为对象,包含:组件外部传递过来,但没有在props配置中声明的属性, 相当于 ```this.$attrs```。
|
||||
- slots: 收到的插槽内容, 相当于 ```this.$slots```。
|
||||
- emit: 分发自定义事件的函数, 相当于 ```this.$emit```。
|
||||
|
||||
|
||||
## 7.计算属性与监视
|
||||
|
||||
### 1.computed函数
|
||||
|
||||
- 与Vue2.x中computed配置功能一致
|
||||
|
||||
- 写法
|
||||
|
||||
```js
|
||||
import {computed} from 'vue'
|
||||
|
||||
setup(){
|
||||
...
|
||||
//计算属性——简写
|
||||
let fullName = computed(()=>{
|
||||
return person.firstName + '-' + person.lastName
|
||||
})
|
||||
//计算属性——完整
|
||||
let fullName = computed({
|
||||
get(){
|
||||
return person.firstName + '-' + person.lastName
|
||||
},
|
||||
set(value){
|
||||
const nameArr = value.split('-')
|
||||
person.firstName = nameArr[0]
|
||||
person.lastName = nameArr[1]
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
### 2.watch函数
|
||||
|
||||
- 与Vue2.x中watch配置功能一致
|
||||
|
||||
- 两个小“坑”:
|
||||
|
||||
- 监视reactive定义的响应式数据时:oldValue无法正确获取、强制开启了深度监视(deep配置失效)。
|
||||
- 监视reactive定义的响应式数据中某个属性时:deep配置有效。
|
||||
|
||||
```js
|
||||
//情况一:监视ref定义的响应式数据
|
||||
watch(sum,(newValue,oldValue)=>{
|
||||
console.log('sum变化了',newValue,oldValue)
|
||||
},{immediate:true})
|
||||
|
||||
//情况二:监视多个ref定义的响应式数据
|
||||
watch([sum,msg],(newValue,oldValue)=>{
|
||||
console.log('sum或msg变化了',newValue,oldValue)
|
||||
})
|
||||
|
||||
/* 情况三:监视reactive定义的响应式数据
|
||||
若watch监视的是reactive定义的响应式数据,则无法正确获得oldValue!!
|
||||
若watch监视的是reactive定义的响应式数据,则强制开启了深度监视
|
||||
*/
|
||||
watch(person,(newValue,oldValue)=>{
|
||||
console.log('person变化了',newValue,oldValue)
|
||||
},{immediate:true,deep:false}) //此处的deep配置不再奏效
|
||||
|
||||
//情况四:监视reactive定义的响应式数据中的某个属性
|
||||
watch(()=>person.job,(newValue,oldValue)=>{
|
||||
console.log('person的job变化了',newValue,oldValue)
|
||||
},{immediate:true,deep:true})
|
||||
|
||||
//情况五:监视reactive定义的响应式数据中的某些属性
|
||||
watch([()=>person.job,()=>person.name],(newValue,oldValue)=>{
|
||||
console.log('person的job变化了',newValue,oldValue)
|
||||
},{immediate:true,deep:true})
|
||||
|
||||
//特殊情况
|
||||
watch(()=>person.job,(newValue,oldValue)=>{
|
||||
console.log('person的job变化了',newValue,oldValue)
|
||||
},{deep:true}) //此处由于监视的是reactive素定义的对象中的某个属性,所以deep配置有效
|
||||
```
|
||||
|
||||
### 3.watchEffect函数
|
||||
|
||||
- watch的套路是:既要指明监视的属性,也要指明监视的回调。
|
||||
|
||||
- watchEffect的套路是:不用指明监视哪个属性,监视的回调中用到哪个属性,那就监视哪个属性。
|
||||
|
||||
- watchEffect有点像computed:
|
||||
|
||||
- 但computed注重的计算出来的值(回调函数的返回值),所以必须要写返回值。
|
||||
- 而watchEffect更注重的是过程(回调函数的函数体),所以不用写返回值。
|
||||
|
||||
```js
|
||||
//watchEffect所指定的回调中用到的数据只要发生变化,则直接重新执行回调。
|
||||
watchEffect(()=>{
|
||||
const x1 = sum.value
|
||||
const x2 = person.age
|
||||
console.log('watchEffect配置的回调执行了')
|
||||
})
|
||||
```
|
||||
|
||||
## 8.生命周期
|
||||
|
||||
- Vue3.0中可以继续使用Vue2.x中的生命周期钩子,但有有两个被更名:
|
||||
- ```beforeDestroy```改名为 ```beforeUnmount```
|
||||
- ```destroyed```改名为 ```unmounted```
|
||||
- Vue3.0也提供了 Composition API 形式的生命周期钩子,与Vue2.x中钩子对应关系如下:
|
||||
- `beforeCreate`===>`setup()`
|
||||
- `created`=======>`setup()`
|
||||
- `beforeMount` ===>`onBeforeMount`
|
||||
- `mounted`=======>`onMounted`
|
||||
- `beforeUpdate`===>`onBeforeUpdate`
|
||||
- `updated` =======>`onUpdated`
|
||||
- `beforeUnmount` ==>`onBeforeUnmount`
|
||||
- `unmounted` =====>`onUnmounted`
|
||||
|
||||
## 9.自定义hook函数
|
||||
|
||||
- 什么是hook?—— 本质是一个函数,把setup函数中使用的Composition API进行了封装。
|
||||
|
||||
- 类似于vue2.x中的mixin。
|
||||
|
||||
- 自定义hook的优势: 复用代码, 让setup中的逻辑更清楚易懂。
|
||||
|
||||
|
||||
|
||||
## 10.toRef
|
||||
|
||||
- 作用:创建一个 ref 对象,其value值指向另一个对象中的某个属性。
|
||||
- 语法:```const name = toRef(person,'name')```
|
||||
- 应用: 要将响应式对象中的某个属性单独提供给外部使用时。
|
||||
|
||||
|
||||
- 扩展:```toRefs``` 与```toRef```功能一致,但可以批量创建多个 ref 对象,语法:```toRefs(person)```
|
||||
|
||||
|
||||
# 三、其它 Composition API
|
||||
|
||||
## 1.shallowReactive 与 shallowRef
|
||||
|
||||
- shallowReactive:只处理对象最外层属性的响应式(浅响应式)。
|
||||
- shallowRef:只处理基本数据类型的响应式, 不进行对象的响应式处理。
|
||||
|
||||
- 什么时候使用?
|
||||
- 如果有一个对象数据,结构比较深, 但变化时只是外层属性变化 ===> shallowReactive。
|
||||
- 如果有一个对象数据,后续功能不会修改该对象中的属性,而是生新的对象来替换 ===> shallowRef。
|
||||
|
||||
## 2.readonly 与 shallowReadonly
|
||||
|
||||
- readonly: 让一个响应式数据变为只读的(深只读)。
|
||||
- shallowReadonly:让一个响应式数据变为只读的(浅只读)。
|
||||
- 应用场景: 不希望数据被修改时。
|
||||
|
||||
## 3.toRaw 与 markRaw
|
||||
|
||||
- toRaw:
|
||||
- 作用:将一个由```reactive```生成的<strong style="color:orange">响应式对象</strong>转为<strong style="color:orange">普通对象</strong>。
|
||||
- 使用场景:用于读取响应式对象对应的普通对象,对这个普通对象的所有操作,不会引起页面更新。
|
||||
- markRaw:
|
||||
- 作用:标记一个对象,使其永远不会再成为响应式对象。
|
||||
- 应用场景:
|
||||
1. 有些值不应被设置为响应式的,例如复杂的第三方类库等。
|
||||
2. 当渲染具有不可变数据源的大列表时,跳过响应式转换可以提高性能。
|
||||
|
||||
## 4.customRef
|
||||
|
||||
- 作用:创建一个自定义的 ref,并对其依赖项跟踪和更新触发进行显式控制。
|
||||
|
||||
- 实现防抖效果:
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<input type="text" v-model="keyword">
|
||||
<h3>{{keyword}}</h3>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import {ref,customRef} from 'vue'
|
||||
export default {
|
||||
name:'Demo',
|
||||
setup(){
|
||||
// let keyword = ref('hello') //使用Vue准备好的内置ref
|
||||
//自定义一个myRef
|
||||
function myRef(value,delay){
|
||||
let timer
|
||||
//通过customRef去实现自定义
|
||||
return customRef((track,trigger)=>{
|
||||
return{
|
||||
get(){
|
||||
track() //告诉Vue这个value值是需要被“追踪”的
|
||||
return value
|
||||
},
|
||||
set(newValue){
|
||||
clearTimeout(timer)
|
||||
timer = setTimeout(()=>{
|
||||
value = newValue
|
||||
trigger() //告诉Vue去更新界面
|
||||
},delay)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
let keyword = myRef('hello',500) //使用程序员自定义的ref
|
||||
return {
|
||||
keyword
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
|
||||
|
||||
## 5.provide 与 inject
|
||||
|
||||
<img src="https://v3.cn.vuejs.org/images/components_provide.png" style="width:300px" />
|
||||
|
||||
- 作用:实现<strong style="color:#DD5145">祖与后代组件间</strong>通信
|
||||
|
||||
- 套路:父组件有一个 `provide` 选项来提供数据,后代组件有一个 `inject` 选项来开始使用这些数据
|
||||
|
||||
- 具体写法:
|
||||
|
||||
1. 祖组件中:
|
||||
|
||||
```js
|
||||
setup(){
|
||||
......
|
||||
let car = reactive({name:'奔驰',price:'40万'})
|
||||
provide('car',car)
|
||||
......
|
||||
}
|
||||
```
|
||||
|
||||
2. 后代组件中:
|
||||
|
||||
```js
|
||||
setup(props,context){
|
||||
......
|
||||
const car = inject('car')
|
||||
return {car}
|
||||
......
|
||||
}
|
||||
```
|
||||
|
||||
## 6.响应式数据的判断
|
||||
|
||||
- isRef: 检查一个值是否为一个 ref 对象
|
||||
- isReactive: 检查一个对象是否是由 `reactive` 创建的响应式代理
|
||||
- isReadonly: 检查一个对象是否是由 `readonly` 创建的只读代理
|
||||
- isProxy: 检查一个对象是否是由 `reactive` 或者 `readonly` 方法创建的代理
|
||||
|
||||
# 四、Composition API 的优势
|
||||
|
||||
## 1.Options API 存在的问题
|
||||
|
||||
使用传统OptionsAPI中,新增或者修改一个需求,就需要分别在data,methods,computed里修改 。
|
||||
|
||||
|
||||
|
||||
## 2.Composition API 的优势
|
||||
|
||||
我们可以更加优雅的组织我们的代码,函数。让相关功能的代码更加有序的组织在一起。
|
||||
|
||||
|
||||
|
||||
|
||||
# 五、新的组件
|
||||
|
||||
## 1.Fragment
|
||||
|
||||
- 在Vue2中: 组件必须有一个根标签
|
||||
- 在Vue3中: 组件可以没有根标签, 内部会将多个标签包含在一个Fragment虚拟元素中
|
||||
- 好处: 减少标签层级, 减小内存占用
|
||||
|
||||
## 2.Teleport
|
||||
|
||||
- 什么是Teleport?—— `Teleport` 是一种能够将我们的<strong style="color:#DD5145">组件html结构</strong>移动到指定位置的技术。
|
||||
|
||||
```vue
|
||||
<teleport to="移动位置">
|
||||
<div v-if="isShow" class="mask">
|
||||
<div class="dialog">
|
||||
<h3>我是一个弹窗</h3>
|
||||
<button @click="isShow = false">关闭弹窗</button>
|
||||
</div>
|
||||
</div>
|
||||
</teleport>
|
||||
```
|
||||
|
||||
## 3.Suspense
|
||||
|
||||
- 等待异步组件时渲染一些额外内容,让应用有更好的用户体验
|
||||
|
||||
- 使用步骤:
|
||||
|
||||
- 异步引入组件
|
||||
|
||||
```js
|
||||
import {defineAsyncComponent} from 'vue'
|
||||
const Child = defineAsyncComponent(()=>import('./components/Child.vue'))
|
||||
```
|
||||
|
||||
- 使用```Suspense```包裹组件,并配置好```default``` 与 ```fallback```
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div class="app">
|
||||
<h3>我是App组件</h3>
|
||||
<Suspense>
|
||||
<template v-slot:default>
|
||||
<Child/>
|
||||
</template>
|
||||
<template v-slot:fallback>
|
||||
<h3>加载中.....</h3>
|
||||
</template>
|
||||
</Suspense>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
# 六、其他
|
||||
|
||||
## 1.全局API的转移
|
||||
|
||||
- Vue 2.x 有许多全局 API 和配置。
|
||||
- 例如:注册全局组件、注册全局指令等。
|
||||
|
||||
```js
|
||||
//注册全局组件
|
||||
Vue.component('MyButton', {
|
||||
data: () => ({
|
||||
count: 0
|
||||
}),
|
||||
template: '<button @click="count++">Clicked {{ count }} times.</button>'
|
||||
})
|
||||
|
||||
//注册全局指令
|
||||
Vue.directive('focus', {
|
||||
inserted: el => el.focus()
|
||||
}
|
||||
```
|
||||
|
||||
- Vue3.0中对这些API做出了调整:
|
||||
|
||||
- 将全局的API,即:```Vue.xxx```调整到应用实例(```app```)上
|
||||
|
||||
| 2.x 全局 API(```Vue```) | 3.x 实例 API (`app`) |
|
||||
| ------------------------- | ------------------------------------------- |
|
||||
| Vue.config.xxxx | app.config.xxxx |
|
||||
| Vue.config.productionTip | <strong style="color:#DD5145">移除</strong> |
|
||||
| Vue.component | app.component |
|
||||
| Vue.directive | app.directive |
|
||||
| Vue.mixin | app.mixin |
|
||||
| Vue.use | app.use |
|
||||
| Vue.prototype | app.config.globalProperties |
|
||||
|
||||
|
||||
## 2.其他改变
|
||||
|
||||
- data选项应始终被声明为一个函数。
|
||||
|
||||
- 过度类名的更改:
|
||||
|
||||
- Vue2.x写法
|
||||
|
||||
```css
|
||||
.v-enter,
|
||||
.v-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
.v-leave,
|
||||
.v-enter-to {
|
||||
opacity: 1;
|
||||
}
|
||||
```
|
||||
|
||||
- Vue3.x写法
|
||||
|
||||
```css
|
||||
.v-enter-from,
|
||||
.v-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.v-leave-from,
|
||||
.v-enter-to {
|
||||
opacity: 1;
|
||||
}
|
||||
```
|
||||
|
||||
- <strong style="color:#DD5145">移除</strong>keyCode作为 v-on 的修饰符,同时也不再支持```config.keyCodes```
|
||||
|
||||
- <strong style="color:#DD5145">移除</strong>```v-on.native```修饰符
|
||||
|
||||
- 父组件中绑定事件
|
||||
|
||||
```vue
|
||||
<my-component
|
||||
v-on:close="handleComponentEvent"
|
||||
v-on:click="handleNativeClickEvent"
|
||||
/>
|
||||
```
|
||||
|
||||
- 子组件中声明自定义事件
|
||||
|
||||
```vue
|
||||
<script>
|
||||
export default {
|
||||
emits: ['close']
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
- <strong style="color:#DD5145">移除</strong>过滤器(filter)
|
||||
|
||||
> 过滤器虽然这看起来很方便,但它需要一个自定义语法,打破大括号内表达式是 “只是 JavaScript” 的假设,这不仅有学习成本,而且有实现成本!建议用方法调用或计算属性去替换过滤器。
|
||||
|
||||
- ......
|
||||
Reference in New Issue
Block a user