小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
了解一波Vue3
Vue3正式发布已经过去一年多了,已经有越来越多的组件库、衍生框架都兼容了Vue3,那么Vue3投入到生产环境的比例也越来越大,学习Vue3也刻不容缓了。(当然Vue2是可以用的,不想太累是可以考虑暂时不学)
开始学习之前,当然先了解下和Vue2的区别了,这里建议有Vue2基础的小伙伴可以直接从官网文档入手,本文就是借Vue3开个头,主要还是讲讲Vue3的setup script语法。
<script setup>
import {computed, defineProps, nextTick, onMounted, ref, toRefs, watch} from 'vue';
import yxButton from '../button/index';
// 声明组件接受的props传参
const props = defineProps({
onConfirm: Function,
onCancel: Function,
})
// 声明变量,类似解构
const {
loading,
modelValue,
closable,
maskClosable,
top,
width,
teleport
} = toRefs(props)
// 声明emit方法, update.modalValue 监听:value绑定的值
const emits = defineEmit(['cancel','confirm','update:modelValue','loading']);
// 声明变量
let name = ref('Corey')
console.log(name.value); // 打印变量值
// 声明computed方法
const modalStyle = computed(() => {
const dest = {
width: width.value + 'px',
top: top.value + 'px',
...props.style
}
return dest
})
</script>
一部分常规写法如上,声明变量需要使用到ref()方法,调用变量使用的的name.value,这和Vue2是有所区分的。
此外写computed与watch方法的结构类似,调用的钩子函数不同。
如果是需要写Vue3的setup script语法的小伙伴,建议在使用vsscode时下载一个Vue3 support 插件,调用computed watch等钩子不用手动是import里添加,通过索引会自动添加进去。