programing

Vue 랜덤라우터 컴포넌트

goodsources 2022. 7. 16. 14:04
반응형

Vue 랜덤라우터 컴포넌트

{
    path: '/link_1',
    name: 'link_1',
    component: () => import('./views/Link1.vue')
},

/link_1과 같은 패스를 1개 설정할 수 있지만 이 루트로 이동할 때마다 다른 컴포넌트가 로드됩니다.

Like: /link_1에 접속하면 Link1.vue가 로드되고 사용자가 /link_1에 접속하면 Link2.vue가 표시됩니다.

를 조합하여 사용할 수 있습니다.watch그리고.<component>링크를 클릭할 때마다 동적 구성요소를 렌더링합니다.

예를 들어 다음과 같은 이름의 100개의 컴포넌트가 생성됩니다.component1통해.component100(1개씩 랜덤으로 렌더링 할 때마다<router-link></router-link>를 클릭합니다.

Vue.use(VueRouter)


const router = new VueRouter({
  routes: [{
    path: '/random/:id'
  }]
})



const components = Array.from(Array(100), (x, i) => {
  return {
    name: `component${ i+ 1 }`,
    props: ['lorem'],
    template: `
    <v-card>
    <v-card-title>
    <v-avatar>
    <span class="blue-grey--text headline">${i + 1}</span>
    </v-avatar>
    </v-card-title>
    <v-divider></v-divider>
    <v-card-text>
    <v-container fluid>
      <v-layout justify-center>
        <v-flex>
        <span class="subheader" v-html="lorem"></span>
        </v-flex>
      </v-layout>
    </v-container>
    </v-card-text>
    </v-card>
    `
  }
}).reduce((carry, c) => {
  carry[c.name] = c
  return carry
}, {})

new Vue({
  el: '#app',
  components,
  router,
  computed: {
    current() {
      return `component${this.cid}`
    }
  },
  data() {
    return {
      cid: 1,
      lorem: 'What mystery does the next page hold?'
    }
  },
  watch: {
    '$route': {
      handler: function() {
        let id = this.cid

        while (this.cid === id) {
          id = Math.floor(Math.random() * 100) + 1
        }

        this.cid = id
        
        fetch('https://baconipsum.com/api/?type=all-meat&paras=3&format=html').then(res => res.text()).then(data => {
          this.lorem = data
        })
      }
    }
  }
})
<link href='https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons' rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.js"></script>
<script src="https://unpkg.com/vue-router@3.0.2/dist/vue-router.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.js"></script>


<div id="app">
  <v-app>
    <v-container>
      <v-toolbar app>
        <v-toolbar-items>
          <v-btn :to="`/random/${cid}`" color="deep-orange darken-4" dark>Click Me</v-btn>
        </v-toolbar-items>
      </v-toolbar>
      <v-content>
        <v-slide-x-transition leave-absolute mode="out-in">
          <component :is="current" :lorem="lorem"></component>
        </v-slide-x-transition>
      </v-content>
    </v-container>
  </v-app>
</div>

언급URL : https://stackoverflow.com/questions/53787730/vue-random-router-component

반응형