大良營銷網(wǎng)站建設(shè)價位在線看crm系統(tǒng)
在Vue2項目中可以使用this.$router.push等方法進行路由的跳轉(zhuǎn),但是在Vue3的setup函數(shù)里,并沒有this這個概念,因此如何使用路由方法
1.// 在新的vue-router里面尤大加入了一些方法,比如這里代替this的useRouter,具體使用如下:
//引入路由函數(shù)
import { useRouter } from "vue-router";
//使用
setup() {
? ? //初始化路由
? ? const router = useRouter();
? ? router.push({
? ? ? ? path: "/"
? ? });
? ??
? ? return {};
}
?
2.在vue2中可以通過this來訪問到$refs,vue3中由于沒有this所以獲取不到了,但是官網(wǎng)中提供了方法來獲取:
<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.關(guān)于element在vue3的使用方法,沒有this.$message等方法解決方案
<template>
? <button @click="doLogin">登錄</button>
</template>
<script>
import { getCurrentInstance } from 'vue'
export default {
? name: 'Test',
? setup () {
? ? const instance = getCurrentInstance() // vue3提供的方法,創(chuàng)建類似于this的實例
? ? const doLogin = () => {
? ? ? instance.proxy.$message({ type: 'error', text: '登錄失敗' }) // 類似于this.$message()
? ? }
? ? return { doLogin }
? },
? ?// 如果想試用this.$message,須在mounted鉤子函數(shù)中,setup中沒有this實例,
? ?//但vue3.0中還是建議在setup函數(shù)中進行邏輯操作
? mounted () {
? ? this.$message({ type: 'error', text: '登錄失敗' })
? }
}
</script>
?