props在VSCode中默认类型推导出错
问题描述
调用 props.xxx 的时候会报错。props 的类型推导不正确。
问题排查
一开始不知道 Vue3 中对 props 有进行默认的类型推导,所以我给 props 写了一个 Interface ,并在使用的时候将 props 的类型定义为我自己写的 Interface 。 如下:
interface IBadgeProps {count: numberdot: booleanoverflowCount: number | stringclassName: stringshowZero: booleantext: stringstatus: stringtype: stringoffset: number[]color: string}...setup(props: IBadgeProps) {}
这样就不会在使用 props.xxx 的时候报错了。
后来经过提醒,才知道 Vue3 会对 props 默认进行类型推导的,并不需要自己写一个 Interface 。
那么是什么导致类型推导出错呢?
于是将 props 传值逐个筛选,最终发现是 validator 导致的。
我的写法是:
status: {validator(value: string) {return oneOf(value, ['success', 'processing', 'default', 'error', 'warning'])}},
在 vue-next 的 issue 2474 中有提到这个问题。将 validator 换成箭头函数的写法即可解决这一问题。
解决方案
将 validator 写成箭头函数
status: {validator: (value: string): boolean => {return oneOf(value, ['success', 'processing', 'default', 'error', 'warning'])}},
这个时候再看 props 的类型推导也正确了
补充:
https://v3.cn.vuejs.org/guide/typescript-support.html#%E6%B3%A8%E8%A7%A3-props
根据 vue3 官方文档中说:
import { defineComponent, PropType } from 'vue'interface Book {title: stringyear?: number}const Component = defineComponent({props: {bookA: {type: Object as PropType<Book>,// 请务必使用箭头函数default: () => ({title: 'Arrow Function Expression'}),validator: (book: Book) => !!book.title},bookB: {type: Object as PropType<Book>,// 或者提供一个明确的 this 参数default(this: void) {return {title: 'Function Expression'}},validator(this: void, book: Book) {return !!book.title}}}})
Write operation failed: computed value is readonly
问题描述
问题排查
vue3 的文档中说道:
computed 接受一个 getter 函数,并为从 getter 返回的值返回一个不变的响应式 ref 对象。 或者,它也可以使用具有 get 和 set 函数的对象来创建可写的 ref 对象。
所以我怀疑是我写的代码中修改 computed 的返回值但是没有用 set 函数。于是重新看了一遍代码,发现并没有修改 computed 的值。
最终排查到是 模板引用 ref 与 其中一个 computed 重名了,修改其中一个名字就不会出现这个错误。
这时我本来的写法:
<template><span ref="badge"><sup v-show="badge"></sup></span></template><script lang="ts">import { computed, defineComponent } from 'vue'export default defineComponent({name: 'Badge',setup() {const badge = computed(() => {return true})return {badge}}})</script>
可以看到 ref 中的 badge 与组合式 api 里的 computed 里的 badge 重名了。
看了文档:在组合式 API 中使用 template refs 。在使用组合式 api 时,响应式引用和模板引用的概念是统一的。为了获得对模板元素或组件实例的引用,我们可以像往常一样声明 ref 并从 setup() 返回。
解决方案
将 computed 的 badge 改名字,同时声明 ref 作为组件实例的引用并从 setup 返回。
<template><span ref="badge"><sup v-show="badgeShow"></sup></span></template><script lang="ts">import { ref, computed, defineComponent } from 'vue'export default defineComponent({name: 'Badge',setup() {const badge = ref(null);const badgeShow = computed(() => {return true})return {badge,badgeShow}}})</script>
总结
在 Vue2 中 ref 与 computed 中的方法名重名也不会造成冲突,但是在 Vue3 中使用组合式 api 时,响应式引用和模板引用的概念是统一的,所以当我们的模板引用 ref=”xxx” 与响应式引用 let xxx = ref(1); 中的 xxx 重名时,会发生错误,编译器会把模板引用与响应式引用当成同一个值,造成意想不到的错误。可以看下面一个简单的例子:
<template><div class="hello"><div ref="test"><span>{{test}}</span></div></div></template><script>import { ref } from "vue"export default {name: 'HelloWorld',props: {msg: String},setup() {let test = ref(1)return {test}},methods: {}}</script>
最终 test 变成 "[object HTMLDivElement]" 。不是我们想要的结果。
因此要注意:不要让模板引用的名字与响应式引用的名字重名了。
Vue3全局配置
Vue 的 2.x 版本有很多的全局 API 和配置,它们会在全局范围内改变 Vue 的行为。
比如常见的全局 API 有:Vue.component / Vue.mixin / Vue.extend / Vue.nextTick;
常见的全局配置有:Vue.config.slient / Vue.config.devtools / Vue.config.productionTip
比如,如果你想创建一个全局的组件:
Vue.component('trump-sucks', {data: () => ({ position: 'America president' }),template: `<h1>Trump is the worst ${position}</h1>`;});
或者声明一个全局指令:
Vue.directive('focus', {inserted: el => {console.log('聚焦!');el.focus();},});
这样确实比较方便,但是会造成一些问题。由同一个 Vue 构造函数创建的 Vue 实例都会共享来自构造函数的全局配置。
为了规避这些问题,Vue3 引入了应用实例的概念。
调用 createApp 会返回一个应用实例。
import { createApp } from 'vue';const app = createApp();
应用实例会暴露一个当前全局 API 的子集。在这个重构工作中, Vue 团队秉承的经验法则是:任何会在全局范围内影响 Vue 行为的 API 都会被迁移至应用实例中去。
| 2.x的全局API | 3.x的应用实例API |
|---|---|
| Vue.config | app.config |
| Vue.config.productionTip | 移除 |
| Vue.config.ignoredElements | app.config.isCustomElement |
| Vue.component | app.component |
| Vue.directive | app.directive |
| Vue.mixin | app.mixin |
| Vue.use | app.use |
其他不会在全局影响 Vue 行为的 api 都已改造为具名导出的构建方式,为了支持 TreeShaking 。
在使用 createApp(VueInstance) 得到一个应用实例后,这个应用实例就可以用来把整个 Vue 跟实例挂载到页面上了:
import { createApp } from 'vue';import MyApp from './MyApp.vue';const app = createApp(MyApp);app.mount('#app');
上面提到的全局组件和全局指令在 Vue3 用下面的写法:
app.component('trump-sucks', {data: () => ({ position: 'America president', }),template: `<h1>Trump is the worst ${position}</h1>`;});app.directive('focus', {inserted: el => {console.log('聚焦!');el.focus();},});// 至此,所有在 app 所包含的组件树内创建的 Vue 实例才会共享 trump-sucks 这个组件和 focus 这个指令,而 Vue 构造函数并没有被污染。
参考链接:https://segmentfault.com/a/1190000023462887
this
在 Vue2 中,我们访问 data 或 props 中的变量,都是通过类似 this.number 这样的形式去获取的,但要特别注意的是,在 setup 中, this 指向的是 undefined ,也就是说不能再向 Vue2 一样通过 this 去获取变量了。
那么到底该如何获取到 props 中的数据呢?
其实 setup 函数还有两个参数,分别是 props 、 context ,前者存储着定义当前组件允许外界传递过来的参数名称以及对应的值;后者是一个上下文对象,能从中访问到 attr 、emit 、slots 。其中 emit 就是我们熟悉的 Vue2 中与父组件通信的方法,可以直接拿来调用。
事件API:$on, $off, $once 弃用
在 Vue3 中,从实例中移除了 $on , $off 和 $once 方法, $emit 仍然是现有 API 的一部分,因为它用于触发由父组件以声明方式附加的事件处理程序。
可用通过使用 mitt 来替换。
使用方法:http://bbs.itying.com/topic/5fbb23c92afeb47d24964422
- 安装 mitt
在 utlis 中新建 event.tsyarn add mitt
在 App.vue 中进行监听import mitt from 'mitt'const emitter = mitt()export default emitter
在 HelloWorld.vue 中进行事件发布import emitter from '../utils/event.ts'export default {// ...setup() {mitter.on('test', () => {console.log('mitt')})}}
import emitter from '../utils/event.ts'export default {// ...setup () {mitter.emit('test', 'a')}}
$el 的替代方法
在 Vue3文档 中提到:推荐使用模板引用来直接获取 DOM 元素。It is recommended to use template refs for direct access to DOM elements instead of relying on $el.
因此,如果我们在 setup 中需要使用到 $el 。我们可以在根结点中使用一个模板引用来获取到根节点的 dom 树。可以参考下面的代码:
<template><div ref="root"><h1 @click="test">Hello World</h1></div></template><script>import { ref } from 'vue'export default {setup () {const root = ref(null);const test = () => {console.log(root.value); // 与 $el 一致}return {root,test}}}</script>
$emit 的用法改变
在组合式 api 中想要使用 this.$emits 向父组件传递事件。
在 Vue2.x 中的用法:
// 父组件<template><HelloWorld @on-change="change" /></template><script>export default {methods: {change() {console.log('change');}}}</script>
// 子组件<template><h1 @click="change">hello world</h1></template><script>export default {methods: {change() {this.$emit('on-change')}}}</script>
在 Vue3.x 中则改为:
// 父组件<template><HelloWorld @on-change="change" /></template><script>import { defineComponent } from 'vue'export default defineComponent ({setup() {const change = () => {console.log('change');}return {change}}})</script>
// 子组件<template><h1 @click="change">hello world</h1></template><script>import { defineComponent } from 'vue'export default defineComponent ({emits: ['on-change'],setup(props, { emit }) {const change = () => {emit('on-change')}return {change}}})</script>
详细的原因可参考文档。
v-for 导致 $slots 的结果不一致
首先我们了解一下关于 slots Vue3 做了什么更新。
当我们获取 this.$slots.default 时返回的是一个函数。
computed与watchEffect
担心有人没耐心看完下面一连串的例子,所以先把研究结论写在前头。
主要分为下面三种情况:
**computed**在**template**中被调用:computed函数会在组件初始化时被调用一次,修改computed里的响应式变量时也会重新计算computed,vue2 和 vue3 表现一致。**computed**在**script**中被调用:在 vue2 中,computed函数会在组件初始化时被调用一次,修改computed里的响应式变量时也会重新计算computed。而在 vue3 中都不会。**computed**在**template**和**script**中都没有被调用:computed在初始化时不会被执行,修改computed里的响应式变量时不会重新计算computed,vue2 和 vue3 都不会。
因此如果我想要在 vue3 中根据多个响应式变量来进行计算,但是又不需要在 template 中调用时,可以使用 vue3 中提供的新特性 watchEffect 来实现。
情况一:computed 在 template 中被调用
// vue2<template><div><h1 @click="changeValue">{{result}}</h1></div></template><script>export default {name: 'HelloWorld',data () {return {value: 1}},computed: {result() {console.log('查看computed是否有执行');return this.value + 1}},methods: {changeValue() {this.value = 2}}}</script>
结果是初始化时输出了一次 查看computed是否有执行 ,点击 <h1> 的时候改变了 this.value 的值,所以又触发了一次 result 的执行,又输出了一次 查看computed是否有执行 。
vue3 的示例代码如下:
// vue3<template><div><h1 @click="changeValue">{{result}}</h1></div></template><script>import { ref, computed } from "vue"export default {name: 'HelloWorld',setup() {let value = ref(1)const result = computed(() => {console.log('查看computed是否有执行');return value.value + 1})const changeValue = (() => {value.value = 2})return {result, changeValue}},}</script>
表现结果与上述的 vue2 一致。
情况二:**computed** 在 **script** 中被调用
// vue2<template><div><h1 @click="changeValue">点我呀</h1></div></template><script>export default {name: 'HelloWorld',data () {return {value: 1}},watch: {result(value) {console.log(value);}},computed: {result() {console.log('查看computed是否有执行');return this.value + 1}},methods: {changeValue() {this.value = 2}}}</script>
结果是初始化时输出了一次 查看computed是否有执行 ,点击 <h1> 的时候改变了 this.value 的值,所以又触发了一次 result 的执行,又输出了一次 查看computed是否有执行 。
在 vue3 中的情况:
// vue3<template><div><h1 @click="changeValue">点我呀</h1></div></template><script>import { ref, computed, watch } from "vue"export default {name: 'HelloWorld',setup() {let value = ref(1)watch(() => result, value => console.log(value))const result = computed(() => {console.log('查看computed是否有执行');return value.value + 1})const changeValue = (() => {value.value = 2})return {result, changeValue}},}</script>
初始化时不会执行 result ,点击 <h1> 的时候也不会执行 result 。因此也不会触发 watch 的变化。
这种情况下,vue3 提供了一种解决方案:watchEffect
// vue3<template><div><h1 @click="changeValue">点我呀</h1></div></template><script>import { ref, watchEffect, watch } from "vue"export default {name: 'HelloWorld',setup() {let value = ref(1)let result = ref(0)watch(() => result.value, value => console.log(value))watchEffect(() => {console.log('查看computed是否有执行');result.value = value.value + 1})const changeValue = (() => {value.value = 2})return {result, changeValue}},}</script>
使用了 watchEffect 就可以达到跟上面 vue2 一样的效果了。具体 watchEffect 的用法可以查看官方文档。
情况三:computed 在template 和 script 中都没有被调用
在 vue2 中:
// vue2<template><div><h1 @click="changeValue">点我呀</h1></div></template><script>export default {name: 'HelloWorld',data () {return {value: 1}},computed: {result() {console.log('查看computed是否有执行');return this.value + 1}},methods: {changeValue() {this.value = 2}}}</script>
在 vue3 中:
// vue3<template><div><h1 @click="changeValue">点我呀</h1></div></template><script>import { ref, computed } from "vue"export default {name: 'HelloWorld',setup() {let value = ref(1)const result = computed(() => {console.log('查看computed是否有执行');return value.value + 1})const changeValue = (() => {value.value = 2})return {result, changeValue}},}</script>
上面两段代码中,在初始化和点击 <h1> 的时候都不会触发 result 的执行。
