本片文章主要对Vue3语法进行使用和遇到一些问题的解决方案,不对其深层原理进行讲解。
自从过年以来,已经着手开发过三四个项目了,一边维护着公司的jQuery祖传代码,一边开发着新项目,新项目基本上都是使用vue2和js
初识Vue3
一个月前开启了一个Vue3+TS的新项目,开发的时候也没有系统的学习Vue3的新语法,在掘金上搜索了几篇教程直接就着手开发了,当然项目遇到问题也是现搜现学
项目也要快结束了,梳理一下进行总结,如果你没有用过vue3,看完这篇文章就能直接上手开发vue3项目
我一直觉得实战就是最好的学习方式
废话不多说,上手就是干
使用 setup语法糖,定义的变量和方法不需要 return,组件引入直接使用不再写components
开局
使用 setup语法糖,需要将 setup 添加到 <script> 代码块上:
<template>
<div>根标签一</div>
<div>根标签二</div>
</template>
//lang可以是ts也可以是js
<script setup lang='ts'>
//直接写逻辑
</script>
首先 template模板里可以并级写多个跟标签
<script setup> 中的代码会在每次组件实例被创建的时候执行。
记住: setup它是在 beforeCreate钩子之前调用的。 这是重点后面要考
响应式 ref,reactive
Vue3有两个常用的定义响应式数据的方式,按照官方的来讲:
ref通常定义基础数据类型,在函数里使用ref 值需要使用变量名.value但是在模板中使用的时候会自动解包,直接调用变量名即可。reactive通常定义复杂数据类型,使用时直接调用变量名即可
<template>
<div>{{name}}</div>
<div>{{age}}</div>
<div>{{arr}}</div>
</template>
<script setup>
// 记住:使用前要先引入
import { ref,reactive } from 'vue'
let name = ref('董员外')
let age = ref(100)
console.log(name.value) //董员外
name.value = 'oldUath'
console.log(name.value) //oldUath
let arr = reactive([])
let obj = reactive({})
console.log(arr) //打印出来是一个Proxy对象
arr.push(1)
console.log(arr)
</script>
虽然说
ref通常定义基础数据类型,但是也可以定义复杂数据类型
如何获取dom元素呢?
vue2使用ref来获取dom元素,vue3也是使用它
<template>
<div ref='domName'>我要获取这个元素</div>
</template>
<script setup>
// 记住:使用前要先引入
import { ref } from 'vue'
let domName = ref(null)
console.log('打印dom元素====',domName.value) // null
</script>
为什么会打印出来null呢?
考点来了: 这是因为
setup是在beforeCreate钩子之前调用的。DOM元素还没挂在上呢,你只能获取一个空呀!
解决方法就是在挂载后再打印元素,引入生命周期onMounted
<template>
<div ref='domName'>我要获取这个元素</div>
</template>
<script setup>
import { ref,onMounted } from 'vue'
let domName = ref(null)
// onMounted的生命周期就相当于vue2的mounted
onMounted(() => {
console.log('打印dom元素====',domName.value)
})
</script>
对变量使用类型注释
据听说Vue3和TypeScript更配哟!!!
开始为变量进行ts类型注释
<template>
<div ref='domName'>我要获取这个元素</div>
<div>{{name}}</div>
<div>{{age}}</div>
<div>{{person}}</div>
</template>
<script setup lang="ts">
import { ref,reactive } from 'vue'
let name = ref<string>('董员外')
let age = ref<number>(100)
// 声明一个数据类型
interface Person {
name: string
age?: number
}
let person:Person = reactive({
name:'dong',
age:18,
})
// DOM元素
let domName = ref<HTMLInputElement | null>(null)
</script>
组件间数据传递props与emit
vue3中使用defineProps来接收父组件传递过来的数据
而且不需要引入 defineProps,直接就能使用
父组件 传递数据
<headMessage
:game-type="gameType"
:group-name="yellowName"
:score="yellowScore"
:time="yellowTime"
:pause-game="pauseGame"
></headMessage>
子组件,接收数据
//子组件接收数据
<script setup lang="ts">
import { reactive } from 'vue'
const props = defineProps<{
gameType: string,
groupName: string,
score: number,
time: Array<number>,
pauseGame: boolean,
}>();
//直接调用
console.log("队伍信息头部页面",props.gameType,props.groupName,props.score, props.time,props.pauseGame)
</script>
emit
使用defineEmits向父组件传递信息,不需要引入 defineEmits
子组件可以通过调用内置的 emit 方法,通过传入事件名称来抛出一个事件:
// 子组件
//子组件
<template>
<div class="blog-post">
<h4>{{ title }}</h4>
<button @click="next">Enlarge text</button>
</div>
</template>
<script setup>
//定义事件名,多个事件可以写到一个数组里
const emit = defineEmits(["next-word","first-end","second-word"])
//触发事件,
const next = ()=>{
//向上抛出
emit('next-word')
//也可以传递参数
emit("first-end",'哈哈哈哈哈哈')
}
</script>
// 父组件
//父组件
<template>
// 接收事件并处罚
<headMessage
@next-word="changeWord"
@first-end="firstWordEndEvent"
></headMessage>
</template>
<script setup>
//定义触发事件
const changeWord = ()=>{
console.log("下一个单词")
}
const firstWordEndEvent = (value)=>{
console.log("能接收到参数======",value)
}
</script>
toRef与toRefs
在项目中,通过props获取传递过来的参数可能会很多,每次调用props.gameType,props.groupName,props.score都带着props有点麻烦,也有可能你从接口那获取一个对象,每次使用里面的值时都带着对象名,比较麻烦
此时就可以用toRef将其解构出来
import { reactive,toRef } from 'vue'
let person = reactive({
name:'dong',
age:18,
})
const { name,age} = toRef(person)
但是toRef有个问题,解构出来的变量不是响应式的,这该怎么解决呢?
替换方案就是用 toRefs,多了个s就是比较nb,可以把解构出来的变量变成响应式的
import { reactive,toRefs } from 'vue'
let person = reactive({
name:'dong',
age:18,
})
const { name,age} = toRefs(person)
定义函数
直接在代码里写,不需要再引入method
<template>
<div>{{count}}</div>
<button @click="add"> + 1 </button>
</template>
<script setup lang="ts">
import { ref } from 'vue'
let count = ref(0)
// 定义一个函数
const add = ()=>{
count.value++
}
// 如果需要立刻执行一次,需要在此处调用
add()
</script>
计算属性 computed
computed使用前要先引入
普通计算属性,不传递参数
<template>
<div>{{mySelf}}</div>
</template>
<script setup lang="ts">
// 记住:使用前要先引入
import { ref,computed } from 'vue'
let name = ref('董员外')
let age = ref(18)
const mySelf = computed(()=>{
return `我叫${name.value},今年${age.value}了`
})
真实的场景中,使用计算属性肯定是要传递参数的
<template>
<div>{{mySelf('暴富')}}</div>
</template>
<script setup lang="ts">
// 记住:使用前要先引入
import { ref,computed } from 'vue'
let name = ref('董员外')
let age = ref(18)
// 传递参数
const mySelf = computed(()=>(target)=>{
return `我叫${name.value},今年${age.value}了,我想=====${target}`
})
侦听器 watch和 watchEffect
watch使用前也要先引入
watch 的第一个参数可以是不同形式的“来源”:它可以是一个 ref (包括计算属性)、一个响应式对象、一个 getter 函数、或多个来源组成的数组:
//首先要引入 watch
import { ref, watch } from 'vue'
const x = ref(0)
const y = ref(0)
// 单个 ref
watch(x, (newValue, oldValue) => {
console.log(newValue, oldValue)
})
// getter 函数
watch(
() => x.value + y.value,
(newValue, oldValue) => {
console.log(newValue, oldValue)
}
)
// 多个来源组成的数组
watch([x, () => y.value], (newValue, oldValue) => {
console.log(newValue, oldValue)
})
当来源是数组时,newValue和oldValue也是数组
注意:在监视reactive定义的响应式数据时,oldValue无法正确获取,不能直接侦听响应式对象的 property。例如:
const obj = reactive({ count: 0 })
// 这不起作用,因为你是向 watch() 传入了一个 number
watch(obj.count, (newValue, oldValue) => {
console.log(newValue, oldValue)
})
此时可以这样解决
const obj = reactive({ count: 0 })
watch(() =>obj.count, (newValue, oldValue) => {
console.log(newValue, oldValue)
})
当需要深度监听时
let obj = reactive({
name:'dong',
age:18,
obj:{
like:'female'
}
})
watch(()=> person.obj,(newValue,oldValue)=>{
console.log(newValue,oldValue)
},{deep:true})
watchEffect 是干啥的?
watchEffect的功能和 watch一样,只不过watchEffect有几个特点
- watchEffect自动默认开启了
immediate:true的功能,也就是立刻监听变化,元素一挂载就执行 - 不用向watch一样传递监听的元素,而是自动监听,watchEffect里面有谁就监听谁
let name = ref('dong')
let age = ref(18)
watchEffect(()=>{
console.log('watchEffect执行了',name)
})
数据管理
全局数据管理的方案有很多,无论是vue官方的vuex方案还是,后起之秀Pinia,都非常优秀,但是我们这个项目也不算太大,就没有使用这两个方案
而是用的vue3新出的一个 store 模式:
用简单的话来说就是我新建一个js或者ts文件,在这里定义一些数据,在全局范围内都可以使用并且修改 //store.js
import { ref, reactive } from 'vue'
let gameData = reactive({
yellowTeam : '黄队',
bkueTeam : '蓝队',
yellowScore : 0,
bkueScore : 0,
win: 'yellowTeam'
})
eport default gameData
在需要的组件里就可以引入gameData,并且可以修改它的值。当数据发生改变时都将自动地更新它们的视图
结尾
这只是一些简单的应用和遇到的一些问题的解决方法,虽然说看完我写得这些能写代码,并且对新API有一些了解,但是系统的看一下官方文档还是很有必要的
- 我正在参与掘金技术社区创作者签约计划招募活动,点击链接报名投稿。