Vue2 + VueRouter 如何通过Props来传递数据?

<div id="app">
    <router-view>
        /* 这里面会根据路由的不同载入相应的组件
         * 对应的组件需要绑定,父类的组件(就是外边包裹的id为app组件)的data,
         * 该如何做呢?
        */
    </router-view> 
    /*
    *  没有上面路由组件的话,像这样就可以了,添加了路由,如何绑定呢?不想使用Vuex
    *  也不想通过使用空的 Vue 实例作为中央事件总线的方式,来传递数据
    * <component :childMsg = "parentMsg"></component>
    */
</div>

Vue.component('component', {
  props: ['parentMsg'],
  ....
  ....
})
阅读 8.3k
2 个回答
<div id="app">
    <router-view :view-data="dataObj"></router-view> 
</div>
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

Vue.component('parentComponent', {    //含有 view-router 的父组件
    data: {
        dataObj: {...}    //要向 view-router 组件传递的数据
    }
})
/*-----------------------------------------*/
Vue.component('subComponent', {        // view-router 
    props: {
        viewData
    },
    repalce: true
  ....
  ....
})

以上是我的做法, 更复杂的逻辑你可以在父组件中判断 router 的 current location, 也就是当前路径, 动态的决定向视图传递的数据

是要在每个路由组件中传递父组件data吗?

<router-view :childMsg = "parentMsg"></router-view>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题