基础知识
1.创建Vue项目,脚手架创建
2.OptionAPI以及CompositionAPI
选项式API 以及 组合式API
| Text Only |
|---|
1
2
3
4
5
6
7
8
9
10
11
12
13 | Vue2 采用了OptionAPI
<script lang="ts">
export default{
name:'app',
data(){
return
}
methods:{
}
computed:{
}
}
</script>
|
| Text Only |
|---|
| Vue3 采用了CompositionAPI
使用setup可以不用编写返回值
<script setup lang="ts">
export default{
name:'app',
let var = 1;
funciton function_name{
}
}
|
2.响应式数据
响应式数据通常需要 ref , reactive 等参数来说明其是响应式数据
| Text Only |
|---|
| import { ref, reactive} from 'vue'
|
ref定义的响应式数据需要在 var.value中才能在js或者ts中访问
3.watch监视器
1. ref定义的数据
2. reactive定义的数据
3. 函数返回一个值(getter函数)
4. 一个包含上述内容的数组
对于情况一
| Vue |
|---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 | <script setup>
import {ref,watch} from 'vue'
let person = ref({
name: '李四'
age:12
})
function changeName(){
person.value.name += '%'
}
function changeAge(){
person.value.age += 1
}
function changePerson(){
person.value = {name:'张三',age:18}
}
watch(person,(newValue,oldValue)=>{
console.log('监视person变化',newValue,oldValue)
},{deep:true, immediate: true})
// person作为对象监视的为对象的地址值
// 这里的第三个参数为可选参数
// deep: 表示深度可以检测
// immediate: 表示可以立即检测数据,包括第一次渲染的数据
</script>
|
上述例子中person监视对象的地址值,如果想要检测深度的person变化,需要增加第三个参数
deep: true 来保证上述情况的满足
停止监视的策略
| Vue |
|---|
1
2
3
4
5
6
7
8
9
10
11
12
13 | <script setup>
import {ref,watch} from 'vue'
let sum = ref(0)
function AddOneToSum(){
sum.value += 1
}
const stopWatch = watch(sum,(newValue,oldValue)=>{
console.log("检测sum值的变化","新",'newValue','旧','oldValue')
if(newValue >= 10){
stopWatch()
}
})
</script>
|
监视reactive创建的对象
| Vue |
|---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 | <script setup>
import {reactive,watch} from 'vue'
person = reactive({
name:'张三',
age:12
})
function changeName(){
person.name += '%'
}
function changeAge(){
person.age += 1
}
function changePerson(){
Object.assign(person,{name:'李四',age:18})
}
watch(person,(new,old)=>{
console.log('person变化')
})
</script>
|