vue3——路由跳转、组件传参

2,521 阅读1分钟

路由跳转

<script setup>
    import { useRoute, useRouter } from 'vue-router'
    const route = useRoute()
    const router = useRouter()
    router.push({
        path: ''
    })
</script>

注意:

  1. useRouter()、useRoute()只能在setup内使用,如果在模块中使用、事件中使用,会报undefined的错,一般在顶部使用。
  2. router里的currentRoute.value可以获取当前路由的path、name、query、params等信息。
  3. router也可以通过导入/route/index.js这个模块获得

组件传参

方式一:通过props

    <child msg="hellow vue3" />
    //子组件
    const props = defineProps({
        msg: {
            type: string
        }
    })
    console.log(props.msg) // 'hellow vue3'

方式二: provide/inject

    //父组件
    provide(()=>{
        return {
            msg: 'hellow vue3'
        }
    })
    //子组件
    inject(['msg'])
    console.log(msg) // hellow vue3

方式三: $attrs

    // 父组件
    <son msg="hellow vue3" @sayHi="sayHi" />
    // 子组件
    <child v-bind="$attrs">
    // 孙组件
    const props = defineProps({
        msg: {
            type: string
        }
    })

注意:vue3已经移除listener,上面父组件中的sayHi事件可以通过listener, 上面父组件中的sayHi事件可以通过attrs往下传

方式四: vuex

    //  /store/index.js
    const { createStore } from 'vuex'
    const store = createStore({
        state: {
            count: 1
        },
        mutations: {
            increment (state) {
                // 变更状态
                state.count++
            }
        }
    })
    export store
    // main.js
    import store  from './store'
    app.use(store)
    //组件
    import { useStore } from 'vuex'
    const store = useStore
    store.commit('increment')

方式五: pinia

    // /store/index
    import {defineStore} from 'pinia'
    export const mystore = defineStore(id,{
        state: () => {
            return {
                 count: 0
            }
        },
        actions: {
            increment(){
                this.count ++
            }
        },
        getters: {}
    })
    // main.js
    import { createPinia } from 'pinia'
    app.use(createPinia())
    // 组件
    import { mystore } from '../store'
    const store = mystore()
    //修改count
    store.count++
    store.increment()
    store.$patch({
        count: store.count++
    })
    store.$patch((state)=>{
        state.count ++
    })

方式六:自建store,例如event bus、provide/inject

方式七:emits

    // 父组件
    <child @getData="getData" />
    // 子组件
    const emit = defineEmits(['getData'])
    emit('getData', 'hellow vue3')

方式八:$parent

    import { getCurrentInstance } from 'vue'
    const instance = getCurrentInstance()
    console.log(instance.parent.ctx)