当前位置: 首页 > news >正文

解决vue3没有this造成的无法使用vue2

在Vue2项目中可以使用this.$router.push等方法进行路由的跳转,但是在Vue3的setup函数里,并没有this这个概念,因此如何使用路由方法

1.// 在新的vue-router里面尤大加入了一些方法,比如这里代替this的useRouter,具体使用如下:
//引入路由函数
import { useRouter } from "vue-router";
//使用
setup() {
    //初始化路由
    const router = useRouter();
    router.push({
        path: "/"
    });
    
    return {};
}
 

2.在vue2中可以通过this来访问到$refs,vue3中由于没有this所以获取不到了,但是官网中提供了方法来获取:

<template>
  <h2 ref="root">姓名</h2>
</template>
<script>
    import { onMounted, ref } from 'vue'
    export default {
        name: 'test9',
        setup(){
            const root  = ref(null)
            onMounted(()=>{
                console.log(root.value);
            })
            return {
                root
            }
        },
    }
</script>

//第二种方法,也可以通过getCurrentInstance来获取
<template>
  <h2 ref="root">姓名</h2>
</template>

<script>
    import { onMounted, ref, getCurrentInstance } from 'vue'

    export default {
        name: 'test9',
        setup(){)
            const {proxy} = getCurrentInstance()
            onMounted(()=>{
                console.log(proxy.$refs.root);
            })
            return {
            }
        },
    }
</script>

3.关于element在vue3的使用方法,没有this.$message等方法解决方案
<template>
  <button @click="doLogin">登录</button>
</template>

<script>
import { getCurrentInstance } from 'vue'
export default {
  name: 'Test',
  setup () {
    const instance = getCurrentInstance() // vue3提供的方法,创建类似于this的实例
    const doLogin = () => {
      instance.proxy.$message({ type: 'error', text: '登录失败' }) // 类似于this.$message()
    }
    return { doLogin }
  },
   // 如果想试用this.$message,须在mounted钩子函数中,setup中没有this实例,
   //但vue3.0中还是建议在setup函数中进行逻辑操作
  mounted () {

    this.$message({ type: 'error', text: '登录失败' })
  }
}
</script>
 

http://www.lryc.cn/news/24695.html

相关文章:

  • 百度前端二面vue面试题指南
  • 【备战面试】每日10道面试题打卡-Day1
  • 服务器重启后jar包自动重启
  • Ubuntu 交叉编译工具链安装
  • Vue3中ref、reactive、toRef、toRefs基本用法和区别
  • python hash 不一致踩坑总结
  • qt5.15 快速安装 国内源
  • JavaScript 对象
  • 数据库设计三大范式
  • cesium学习记录02-vue项目中cesium的配置与使用
  • 【微服务】-认识微服务
  • 容器的线程安全性
  • 如何用Postman测试整套接口?测试流程是什么?
  • 【批处理脚本】-2.1-测试IP连接命令ping
  • 百度“文心一言”携手酷开科技,实现AI智能领域新突破!
  • Elasticsearch索引全生命周期管理一网打尽
  • MySQL的SELECT
  • conda 搭建tensorflow-GPU和pycharm以及VS2022 软件环境配置
  • HACKTHEBOX——Teacher
  • 干货| Vue小程序开发技术原理
  • unity-web端h5记录
  • 基于部标JT808的车载视频监控需求与EasyCVR视频融合平台解决方案设计
  • Grafana邮件及告警配置
  • Springboot Java多线程操作本地文件,加读写锁,阻塞的线程等待运行中的线程执行完再查询并写入
  • WebRTC拥塞控制算法——GCC介绍
  • 大数据技术之Maxwell基础知识
  • 元数据管理实践数据血缘
  • SQL的优化【面试工作】
  • Kotlin 40. Dependency Injection 依赖注入以及Hilt在Kotlin中的使用,系列3:Hilt 注释介绍及使用案例
  • 1000亿数据、30W级qps如何架构?来一个天花板案例