通过本文,可快速了解对于vue3+的setup语法糖,基础业务也可以直接开展。本文中都是经过测试一一试验的,vue版本为^3.2.25
,要注意不同的版本之间,用法有些会有出入
本文也尚在测试使用阶段,后续更多用法会持续更新
生命周期
<script setup>
import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onErrorCaptured, onRenderTracked, onRenderTriggered } from 'vue'
//created,beforeCreate 在setup中已经触发了,所以vue3+已不用
// 组件挂载前
onBeforeMount(() => {})
// 组件挂载后
onMounted(() => {
})
// 组件更新前
onBeforeUpdate(() => {})
// 组件更新后
onUpdated(() => {})
// 组件错误调用后
onErrorCaptured(() => {})
// 跟踪虚拟 DOM 重新渲染时调用
onRenderTracked(() => {})
onRenderTriggered(() => {})
</script>
常用API
<template>
<input v-model="inputVal" @blur="onChange" />
<div>计算属性{{ count }}</div>
</tempate>
<script setup>
import { ref, compouted, watch, getCurrentInstance } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
// 获取vuex-store对象
const Store = useStore()
Store.dispatch('setCount', 1)
// 获取router对象,以及route数据
const Router = useRouter() // Router.push(path) 路由跳转
const Route = useRoute() // Route.query 路由参数
// template中使用的变量也不用return抛出,声明只可使用
const inputVal = ref('default value') // 双向绑定 需要在setup获取/修改双向绑定值,则为inputVal.value
const onChange = (value) => {
// ...do something
}
// 计算属性
const count = computed(() => Store.state.countNum)
// 在页面中使用vue,this实例对象
const { ctx: _this } = getCurrentInstance()
_this.$forceUpdate() // 强制刷新组件
</script>
父组件传参 - defineProps
parent.vue
<template>
<child :info="parentInfo" />
</template>
<script setup>
// 子组件无需注册,引入只可直接使用
import Child from './child.vue'
const parentInfo = { name: '父级元素信息' }
</script>
child.vue
<script setup>
// 获取props传参, defineProps 新版本无需引入
const props = defineProps({
info: {
type: Object,
default: () => ({})
}
})
console.log(props.info) //获取到的父级传来的信息
</script>
子组件传参 - defineEmits
parent.vue
<tmeplate>
<child @getChildInfo="getChildInfo" />
</template>
<script setup>
import Child from './child.vue'
const getChildInfo = (childInfo) => {
console.log(childInfo) // 子组件传递过来的信息
}
</script>
child.vue
<script setup>
const emit = defineEmits(['getChildInfo']) //注册要传递的参数
emit('getChildInfo', { name: '我是子组件' })
</script>
在setup函数中使用
// child
<template>
<button @click="handleClick">点击传出数据</button>
</template>
<script>
export default {
setup (props, context) {
function handleClick () {
context.emit('change', 'date for parent')
}
return { handleClick }
}
}
</script>
绑定样式style
<template>
<div class="col" @click="handleChangeColor">点击更换字体颜色</div>
</template>
<script setup>
import { ref } from 'vue'
const colArr = ['red', 'green', blue]
const col = ref(colArr[0])
const handleChangeColor = (index = 0) => {
col.value = colArr[index]
}
</script>
<style>
.col {
color: v-bind(col)
}
</style>
还有一些详细的单个学习笔记
vue3-学习笔记-获取子组件/dom的ref