programing

Vue Async 구성 요소를 사용하려면 어떻게 해야 합니까?

randomtip 2023. 2. 4. 08:34
반응형

Vue Async 구성 요소를 사용하려면 어떻게 해야 합니까?

larabel 5.4와 vue 2를 사용하고 있는데 버튼을 사용하여 컴포넌트를 비동기식으로 로드하고 싶습니다.My Vue js 컴포넌트는 분리되어 있습니다.예:vue 및 테스트.vue와 나는 그것들을 html 태그로 로드한다.

이것은 내 앱입니다.js:

import './bootstrap';
import example from './components/Example.vue';

Vue.component('example', example);

const app = new Vue({
el: '#app'
});

컴포넌트를 표시하는 장소입니다.

    <How can i use Async components?div id="app">
         <example2></example2> 
    </div>

비동기 컴포넌트를 사용하려면 어떻게 해야 하나요?


아뇨, 당신은 날 이해하지 못하는 것 같아요.컴포넌트 등록입니다.

import './bootstrap';
import example from './components/Example.vue';

Vue.component('example', example);

Vue.component('example2', function (resolve) {

require(['./components/Example2.vue'],resolve)

})


const app = new Vue({
el: '#app'
});

require에서는 디폴트로 해결되었습니다(표시되어 있습니다).컴포넌트를 호출할 때 페이지에서 해결 키와 거부 키를 이 메서드에 건네주는 방법을 모르겠습니다.

vue 2의 비동기 구성 요소를 스타일링 방식으로 사용할 수 있습니다.비동기 컴포넌트를 적절하게 사용하면 프로젝트 로딩 시간을 단축할 수 있습니다.다음과 같이 비동기 컴포넌트를 사용할 수 있습니다.

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router ({
routes: [
  {
    path: '/',
    name:'LandingPage'
    component: () => import('@/containers/LandingPage.vue')
  },
  {
    path: '/login',
    name:'LoginPage'
    component: () => import('@/containers/LoginPage.vue')
  }
]
})

이 구조는 템플릿 내부에 컴포넌트를 로드하는 경우에 적합합니다.

new Vue ({
  el: 'app',
    components: {
      AsyncComponent: () => import ('./AsyncComponent.vue')
    }
})

자세한 것은, www.bdtunnel.com 를 참조해 주세요.

Vue.js의 비동기 컴포넌트의 경우 resolve 인수는 비동기 콜이 성공했을 때 호출되는 함수이므로 require() 콜은 착신된 해결 함수 내에 있어야 합니다.require() 콜의 괄호를 삭제하고 다음과 같이 행 형식을 지정하기만 하면 됩니다.

resolve(require('./components/Example2.vue'))

다음 예에서는 기본을 사용하고 있습니다.setTimeout()비동기 콜을 에뮬레이트합니다.해결 함수는 5초 후에 호출되며 로드됩니다.Example2컴포넌트를 앱에 추가합니다.

를 표시/숨기기 위해Example2버튼 클릭 한 번으로 컴포넌트를 구성하기 위해data()기능.그러면 App.vue의 템플릿을 보시면v-if( https://vuejs.org/v2/guide/conditional.html#v-if) 명령어 추가/추가/삭제Example2컴포넌트를 가상 DOM으로 송수신합니다.당신은 우리를 쉽게 할 수 있었다.v-show(https://vuejs.org/v2/guide/conditional.html#v-show) 명령도 여기에 있습니다.단, 컴포넌트는 그대로 남아서 숨겨져 있습니다.에 대한 자세한 내용을 참조해 주세요.v-ifv-show여기: https://vuejs.org/v2/guide/conditional.html#v-if-vs-v-show이것은 앱에서 모달(modal)을 숨기고 표시하는 매우 일반적인 패러다임입니다.이것이 매우 잘 동작하고 있는 예를 나타냅니다.https://vuejs.org/v2/examples/modal.html

main.discloss.main.discloss.

import Vue from 'vue'
import App from './components/App.vue'

Vue.component('example2', function(resolve, reject) {
  setTimeout(function() {
    resolve(require('./components/Example2.vue'))
  }, 5000)
})

const app = new Vue({
  el: '#app',
  render: h => h(App)
})

예 2.표시하다

<template>
  <div>
    <div>Hello example 2!</div>
  </div>
</template>      

App.vue

<template>
  <div id="app">
    <button type="button" @click="onButtonClick">Click me to add the example2 component</button>
    <example2 v-if="show_example2"></example2>
  </div>
</template>

<script>
  export default {
    name: 'app',
    data() {
      return {
        show_example2: false
      }
    },
    methods: {
      onButtonClick() {
        this.show_example2: true
      }
    }
  }
</script>

VueJs의 설명서에 따르면 버전 2.3 이후 이와 같은 비동기 컴포넌트를 정의할 수 있습니다.

const AsyncComp = () => ({
  // The component to load. Should be a Promise
  component: import('./MyComp.vue'),
  // A component to use while the async component is loading
  loading: LoadingComp,
  // A component to use if the load fails
  error: ErrorComp,
  // Delay before showing the loading component. Default: 200ms.
  delay: 200,
  // The error component will be displayed if a timeout is
  // provided and exceeded. Default: Infinity.
  timeout: 3000
})

컴포넌트와 함께 사용하면 컴포넌트를 동적으로 로드할 수 있습니다.

편집: 언급된 문서에 대한 업데이트된 링크입니다.

해 온 한 의 가가 your your your your your your your your your your your your your your your your your your your your your your your your your your your your your 를 만드는 것이다.example2컴포넌트를 설정합니다.

<template>
  <div>
    <div v-if="inited">
      <div>{{foo}}</div>
      <div>{{bar}}</div>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        foo: '',
        bar: '',
        inited: false
      }
    },
    mounted() {
      var me = this
      axios.get('/my/ajax/call').then(function(response) {
        me.foo = response.data.foo
        me.bar = response.data.bar
        me.inited = true
      })
    }
  }
</script>

기본적으로 컴포넌트가 마운트될 때마다 AJAX 호출이 완료될 때까지 빈 정보로 렌더링되며 이후 반응 데이터가 업데이트되고 Vue가 반응 데이터 요소를 자동으로 업데이트합니다.는, 「표시하지 않는 것」을 할 수 .inited: false하고, 을 「」로 설정합니다.true에서 AJAX 콜백 중 합니다.:v-if="inited" ★★★★★★★★★★★★★★★★★」:v-show="inited"divAJAX 콜이 반환될 때까지 컴포넌트의 내용을 숨깁니다.

Vue 3 - 변경 사항 변경

에는 """가 필요합니다.defineAsyncComponent다음 중 하나:

// vue 2.x
const asyncPage = () => import('./NextPage.vue')

// vue 3.x
const asyncPage = defineAsyncComponent(() => import('./NextPage.vue'))

다른 는 른른른른 another another another another another another another another another another another another anothercomponent의 이름이 「어느쪽인가」로 .loader추가 옵션을 정의하는 경우:

const asyncPageWithOptions = defineAsyncComponent({
  loader: () => import('./NextPage.vue'),
  delay: 200,
  timeout: 3000,
  error: ErrorComponent,
  loading: LoadingComponent
})

문서: https://v3.vuejs.org/guide/migration/async-components.html#_3-x-syntax

언급URL : https://stackoverflow.com/questions/43498126/how-can-i-use-vue-async-components

반응형