【问题标题】:Vue cli passing props (data) through router-linkVue cli 通过 router-link 传递道具(数据)
【发布时间】:2018-12-17 02:06:59
【问题描述】:

我正在使用安装了 vue-router 的 Vue-cli,在我的 App.vue 内部,我有 <router-link to="/about" >About</router-link>,它将在点击时显示 about 组件的内容。现在,我想将 props 数据从 App.vue 传递给 About.vue 组件。在 <router-link to="/about" :myprops="myprops">About</router-link> 中添加 :myprops="myprops" 不起作用,这就是为什么我将以下内容添加到 App.vue

<script>
import About from './components/About.vue';
export default {
  name: 'App',
 components:{'my-about':About}
  data(){return {...}
  },
props:{myprops:[{.....}]}
}
</script>

About.vue 组件中,我使用props:['myprops'] 来获取道具数据并使用{{myprops}} 来显示它。 现在,如果在App.vue 内,我添加&lt;my-about :myprops="myprops"&gt;&lt;/my-about&gt;,那么道具数据将移交给About.vue 并会显示,但About.vue 的内容也会显示在我的App.vue 页面上,而且,它将在About.vue 内重复。我不想要那个。我只需要将myprops 数据传递给About.vue 组件,而不在App.vue 中显示About.vue 内容。 而且,这是我在router/index.js 中的路径代码供参考: { path: '/about', component: About }

我怎样才能做到这一点?

【问题讨论】:

    标签: vue.js vue-component vue-router


    【解决方案1】:

    这里假设你不是 Vue 的初学者。

    1 - 在目标组件上定义一个 prop

    export default {
        name: "MyComponent",
        props: {
            exampleProp: Object
        }
    }
    

    2 - 使用 props: true

    定义路线
    ...
        routes: [
            {
                path: '/mycomponent',
                name: 'MyComponent',
                component: MyComponent,
                props: true
            },
    ...
    

    3 - 在 router-link 上使用路由 name 而不是路径,并将 props 作为参数传递。

    <router-link 
        :to="{ name: 'MyComponent', 
               params: { exampleProp: examplePropValue }}">
        Link to My Component
    </router-link>
    

    【讨论】:

    • 这会弄脏网址吗?生病了一定要试试。谢谢
    • URL 保持干净;只有路径会改变。
    【解决方案2】:

    路由器并不是用来传递数据的。它旨在将 URL 映射到 coponents。所以你可以做的就是将 URL 中的 props 作为参数或查询参数传递。 (如果帽子不符合您的要求,您可能需要真正的状态管理解决方案,如 Vuex)

    必须在路由定义 (see here) 中定义一个参数,而且您似乎不希望这样。

    您可以将信息作为查询参数传递,链接如下所示:

    <router-link :to="{ path: '/about', query: { myprop: 'someValue' }}">
      About
    </router-link>
    

    生成的 URL 最终将如下所示:

    /about?myprop=somevalue
    

    然后,此查询参数在任何组件中都可以作为this.$route.query.myprop 使用。要将其作为实际 prop 传递给 About 组件,您需要 configure the router to do so:

    {
      path: '/about', 
      component: About,
      props(route) {
        return {  myprop: route.query.myprop }
      }
    }
    

    【讨论】:

    • 谢谢,这行得通。顺便说一句,由于我是 Vue 的初学者并且我的背景是 PHP,你认为我应该直接跳入 Vuex 还是坚持使用 Vue。我的目标是使用 wordpress 作为后端,使用 Vue 框架作为前端。我应该把重点放在哪里(学习 Vuex 还是继续学习 Vue)?
    • @LinusBorg 绑定需要在路由器链接:to冒号
    • 好吧,修好了。谢谢!
    猜你喜欢
    • 2015-07-18
    • 1970-01-01
    • 2020-12-21
    • 2018-02-28
    • 2018-01-17
    • 2018-04-27
    • 2019-08-09
    • 2021-03-21
    • 1970-01-01
    相关资源
    最近更新 更多