Vue3简介
About 2 min
详细Vue3基础可参考尚硅谷的课程笔记:ReadMe.md · Marina-37/vue3_vite_ts - 码云 - 开源中国
进阶请参考vue3官网:Vue.js - 渐进式 JavaScript 框架 | Vue.js
Vue3简介
组合式API
(GIF非原创)
- OptionsAPI

- CompositonAPI

和Vue2的区别
- Vue3不要到单独的根标签了
- Vue3有
setup(){}
这个新的配置项 - 实际使用中,更建议通过
<script setup>
这样的语法糖
Ref,Reactive
- reactive :对象类型
- shallowReactive:只有第一层数据是响应式的
<script setup>
import { reactive } from 'vue';
const mydata = reacitive([1, 2, 3])
</script>
- ref:适用于基本类型和对象类型
- 若
ref
接收的是对象类型,内部其实也是调用了reactive
函数。
- 若
- shallowRef
<script setup>
import { ref } from 'vue';
const mydata = ref(0)
//更改时需要的是mydata.value
</script>
- readonly
- shallowReadonly:只有根属性是只读的
- 非响应式
Computed
<script setup>
import { computed } from 'vue';
const mydata = computed(() => {
})
</script>
Watch
<script setup>
import { ref, watch } from 'vue';
const count = ref(0)
watch(count, (newValue, oldValue) => {
console.log(newValue, oldValue)
})
</script>
如果想对一个对象的属性侦听,需要以函数的形式
<script setup>
import { ref, watch } from 'vue';
const count = reactive({
name: 'qqq',
age: 18
})
watch( () => count.age, (newValue, oldValue) => {
console.log(newValue, oldValue)
})
</script>
WatchEffect
这里面写的响应式数据发生变化,就会触发这个函数
<script setup>
import { ref, watchEffect } from 'vue';
const count = reactive({
name: 'qqq',
age: 18
})
watchEffect( () => {
console.log(xxxxxxxxxx)
})
</script>
props
- 若 父传子:属性值是非函数。
- 若 子传父:属性值是函数。
- 子传父之前实际需要父传给子一个函数
<template>
<div class="father">
<h3>父组件,</h3>
<h4>我的车:{{ car }}</h4>
<h4>儿子给的玩具:{{ toy }}</h4>
<Child :car="car" :getToy="getToy"/>
</div>
</template>
<script setup lang="ts" name="Father">
import Child from './Child.vue'
import { ref } from "vue";
// 数据
const car = ref('奔驰')
const toy = ref()
// 接受的方法
function getToy(value:string){
toy.value = value
}
</script>
<template>
<div class="child">
<h3>子组件</h3>
<h4>我的玩具:{{ toy }}</h4>
<h4>父给我的车:{{ car }}</h4>
<button @click="getToy(toy)">玩具给父亲</button>
</div>
</template>
<script setup lang="ts" name="Child">
import { ref } from "vue";
const toy = ref('奥特曼')
//声明接受props
defineProps(['car','getToy'])
</script>
自定义事件-实现子传父
重点:defineEmits(['sent-toy'])
定义 emit('send-toy', 具体数据)
触发
<!--在父组件中,给子组件绑定自定义事件:-->
<Child @send-toy="saveToy"/>
<!--注意区分原生事件与自定义事件中的$event-->
<button @click="toy = $event">测试</button>
//父组件中,自定义事件被触发时所调用的函数:
function saveToy(value:string){
console.log(value)
}
//子组件中,声明事件并触发:
const emit = defineEmits(['sent-toy'])
emit('send-toy', 具体数据)