vue3动态路由添加,列表获取,跳转,传参,router里获取store里的值以及使用方法,页面获取vuex里的state值,ref获取元素宽高,监听vuex里的值
vue3动态路由添加和路由列表获取

import {useRouter} from 'vue-router'

export default defineComponent({
  setup() {
    const router = useRouter(); 
    const dui = [
      {
        path: '/aaa',
        name: 'Aaa',
        component:  () => import('@/views/aaa.vue')
      },
      {
        path: '/firs',
        name: 'Firs',
        component:  () => import('@/views/firs.vue')
      },
      {
        path: '/thre',
        name: 'Thre',
        component:  () => import('@/views/thre.vue')
      },
    ];
    //添加路由
    dui.forEach(res =>{
      router.addRoute(res);
    })
    //获取路由列表
    let lis = router.getRoutes();
  },
})

vue3路由跳转传参

方法一

import router from './router'

  setup() {
  	//点击跳转
    const gorouter = () =>{
      const obj = {
        name:'nihao',
        age:100
      }
      router.push({
        path:'/about',
        query:obj
      });
    }
    return {
      gorouter
    }
  },

方法二

import { useRoute, useRouter} from 'vue-router'

setup() {
    const router = useRouter();
    const route = useRoute();

    const gorouter = () =>{
      const obj = {
        name:'nihao',
        age:100
      }
      router.push({
        path:'/about',
        query:obj
      });
    }
    return {
      gorouter
    }
  },

router里获取store里的值以及使用里面的方法
在router里引入store里的文件就可以拿到
例如:获取store下的modules下的文件里的值

//router文件里
import use from '../store'
import store from '../store/modules/setUserInfo'
let name = store.state.name;
use.commit('方法',)

页面获取vuex里state的某个值(用computed才能实时同步更新)

import { computed, defineComponent,toRaw } from 'vue'
import {useStore} from 'vuex'

setUp(){
	 const store = useStore();
    //获取vuex中setUserInfo模块里state的routerList值
    //如果不是模块化就把setUserInfo去掉就行
    //用computed才能实时同步更新
    let storeData = computed(() =>{
      return store.state.setUserInfo.routerList
    }).value
    
    //得到的是一个proxy值,需要toRaw才能拿到你想要的
    console.log(toRaw(storeData ))//方法一
    console.log(toRaw(store.state.setUserInfo.routerList))//方法二
}

ref获取元素及宽高

<div ref="bigscroll"></div>
setup() {
	const bigscroll = ref(null);
	onMounted(() =>{
		console.log(bigscroll.value)
		console.log(bigscroll.value.offsetWidth)
		console.log(bigscroll.value.clientWidth)
		console.log(bigscroll.value.clientHeight)
	})
	return{
		bigscroll
	}
}

监听vuex里的值

import {useStore} from 'vuex'
setup() {
        const store = useStore();
		watch(()=>store.state.defaultActive,()=>{
		    console.log('??????????')
		})
}
Logo

前往低代码交流专区

更多推荐