1. vue3 全局挂载问题

在vue2中,全局挂载通过Vue.prototype的方式,通过原型定义在每个vue实例中可用

vue2中的方法                                                                                          

在main.js 使用Vue.prototype.$xxx = zzz(zzz可以是变量也可以是import的方法)

// 例子
Vue.prototype.$test = 50 //定义全局变量test的值为50

在需要的页面通过this.$xxx引入

// 例子
alert(this.$test) // 弹出的值为50

 vue3中的方法 (vue3+ts)                                                                        

在vue3中,Vue.prototype无法使用,而且也没有this

在main.ts中使用globalProperties

app.config.globalProperties.$xxx = zzz

// 先通过app创建vue
const app = createApp(App)
app.mount('#app')
app.config.globalProperties.$test = 50 // test变量值为50

在需要引用的vue实例中先引入getCurrentInstance

import { getCurrentInstance } from 'vue'

 定义proxy

const { proxy } = getCurrentInstance()

在需要使用全局的地方用proxy.$xxx使用

proxy.$xxx

console.log(proxy.$test) // 50

2. getCurrentInstance报错,

proxy' does not exist on type 'ComponentInternalInstance | null'

可以添加ts忽略去解决

  // @ts-ignore

  // @ts-ignore
  const { proxy } = getCurrentInstance()

新建useCurrentInstance.ts(转载不知道原理 求解) 转自Vue3 getCurrentInstance与ts结合使用的问题 - Mica - 博客园 (cnblogs.com)

新建 hooks\useCurrentInstance.ts

import { ComponentInternalInstance, getCurrentInstance } from 'vue'
export default function useCurrentInstance() {
    const { appContext } = getCurrentInstance() as ComponentInternalInstance
    const globalProperties = appContext.config.globalProperties
    return {
        globalProperties
    }
}

组件中使用

// 先引入文件
import useCurrentInstance from "@/hooks/useCurrentInstance";
...
// 在setup 中使用处理
const { globalProperties } = useCurrentInstance();

3. Type 'boolean' is not assignable to type 'Ref<boolean>'.

类型boolean不可以分配给Ref<boolean>

错误代码:

setup () {
let awardIsOver = ref(true)
····
const hideMask = () => {
      awardIsOver = false
    }
    return {
    hideMask
    }
}

一个点击事件,点击以后将awardIsOver的值变成false

正确代码:

setup () {
const awardIsOver = ref(true)
····
const hideMask = () => {
      awardIsOver.value = false
    }
    return {
    hideMask
    }
}

不是ts类型的问题,是vue3的ref响应式需要加value才是真正的值,ref返回的是个对象

4. vue3 watch监听

如果要监听props父组件传给子组件的值,语法如下 script setup同样适用

watch(() => props, (newValue, oldValue) => {
console.log(newValue, oldValue)
})

5. vue3 使用子组件中的方法

 在父组件中,子组件绑定一个ref, 定义一个变量名与ref名一致

const modalRef = ref() // 子组件方法 modalRef为自定义

在父组件中,通过xxx.value.yyy() 的形式调用子组件中方法 xxx为ref定义的名字, yyy为子组件的方法名

  modalRef.value.showModal()

Logo

前往低代码交流专区

更多推荐