vue3开发踩坑
在新的项目尝试使用vue3,由于一开始使用vite构建打包后文件有问题,目前使用vue-cli,遇到的坑记录:
自定义全局变量
原vue2
写法是直接绑定在Vue.prototype
vue3
中定义:
// main.ts
const app = createApp(App)
app.config.globalProperties.$test = 1;
通过 getCurrentInstance
获取实例,在setup()
中应用:
import {getCurrentInstance} from 'vue';
const test = getCurrentInstance()?.appContext.config.globalProperties.$test;
个人认为,这种写法相比于
vue2
直接通过this.$test 获取,较于繁琐,有点鸡肋
script setup 通过vue-cli
构建后页面显示空白
<script setup>
目前还是一种实验性语法糖,
<script setup>
import { ref } from 'vue'
export const test1 = ref(0)
export const test = () => test1.value++
</script>
当使用 <script setup>
时,组件在编译过程中j将代码放到setup函数中运行,然后把导出的变量定义到上下文中,并包含在setup函数返回的对象中。
在使用该语法糖的过程中发现,当项目是使用vue-cli
构建,打包后在生产环境下,使用该语法糖的组件在页面会显示空白,可能因为目前还是实验性语法,脚手架不能很好的支持
目前在项目中还是尽量不要使用这个语法糖
数据绑定性能问题:若页面不需要,则避免将字段双向绑定
具体的场景:
目前有一个需求是实现多个echarts
图表功能,若将初始化的chart对象绑定在state上,页面会出现卡顿,图表动画效果失效的问题
避坑:
若一些字段不需要在页面上使用,则避免双向绑定,尤其一些很大的对象,绑定需谨慎
vue data内部不支持字段以$和_开头,会有警告
当使用_
和 $
定义变量命名,会报警告,内部并不支持
警告信息:
[Vue warn]: setup() return property "_openCarousel" should not start with "$" or "_" which are reserved prefixes for Vue internals.
ref vue2
与 vue3
写法上的区别
<table ref="tableRef" />
-
vue2
this.$refs.tableRef // 调用 `vue3`
-
vue3
setup() { const tableRef = ref<any>(null); return { tableRef } }
避坑: 需定定义字段,并暴露
props 和emits
在vue3
中,父子组件传值的 props
和 emits
写法更加规范:
-
v-model
变化:v-model:value
等同于props: 'value'
和emit('update:value')
<child-component v-model:value="myValue"></child-component>
-
需要指定
emits
export default defineComponent({ emits: ['update:value', 'otherEmit'], setup(props, { emit }) { emit('update:value') emit('otherEmit') }, })
一旦页面报错,然后路由跳转会有问题,跳不过去
todo 还没找到原因