【问题标题】:Router Vue, call the same component with different templateRouter Vue,使用不同的模板调用相同的组件
【发布时间】:2020-11-13 16:22:25
【问题描述】:

使用“router-link”,我想多次调用同一个组件 通过传递一个不同的模板。 但我不明白怎么做。 有人可以帮我吗?

navbar.vue:

<template>
 <div>
    <div>TITLE</div>
        <div class="row">
            <router-link PASS-TEMPLATE-TO-SLOT="<p>hello1</p>" :to="{ name: 'generic-comp'}"> TEST1 </router-link>
            <router-link PASS-TEMPLATE-TO-SLOT="<p>hello2</p>":to="{ name: 'generic-comp'}"> TEST2 </router-link>
            <router-link PASS-TEMPLATE-TO-SLOT="<p>hello3</p>":to="{ name: 'generic-comp'}"> TEST3 </router-link>
        </div>
    <router-view></router-view>
</div>

generic-comp.vue:

<template>
    <div>
        <h1>Title</h1>
        <slot></slot>
    </div>
</template>

【问题讨论】:

    标签: laravel vue.js vue-router


    【解决方案1】:

    使用 props 的路由传递 组件 / raw html 应该是一种解决方案。

    如下演示:

    const Generic = { 
      render: function (createElement) {
        return createElement('div', [
          createElement('h3', 'Title'),
          createElement(this.routeSlot, { props: {interval: this.property1}}),
          this.extraSlot && createElement(Vue.component('v-my-slot', {template:this.extraSlot})) // construct one component with raw html
        ])
      },
      props: ['routeSlot', 'property1', 'extraSlot']
    }
    
    const Foo = { 
      template: '<div><h4>foo {{counter}} </h4><button @click="add()">Click Me!</button></div>',
      data () { return {counter: 0}},
      props: {
        interval: {
          type: Number,
          default: 1
        }
      },
      methods: {
        add: function () { 
          this.counter += this.interval 
        }
      }
    }
    const Bar = { 
      template: '<div><h4>bar {{interval}} </h4></div>',
      props: ['interval']
    }
    const routes = [
      { path: '/foo', component: Generic, props: {routeSlot: Foo, property1: 2} },
      { path: '/bar', component: Generic, props: {routeSlot: Bar, property1: 3, extraSlot: '<p style="color:red">Like a Slot</p>'} }
    ]
    const router = new VueRouter({
      routes
    })
    const app = new Vue({
      router
    }).$mount('#app')
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
    <div id="app">
      <p>
        <router-link to="/foo">Go to Foo</router-link>
        <router-link to="/bar">Go to Bar</router-link>
      </p>
      <router-view></router-view>
    </div>

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-16
    • 2020-04-13
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 2019-10-27
    相关资源
    最近更新 更多