programing

JS 파일이 외부에서 로드된 경우 Vue에서 공동 구성 요소를 등록할 수 없습니다.

prostudy 2022. 7. 7. 22:18
반응형

JS 파일이 외부에서 로드된 경우 Vue에서 공동 구성 요소를 등록할 수 없습니다.

.vue가 아닌 일반 js 파일 및 인라인 템플릿에서 vue를 사용하고 있습니다.서브페이지에 따라 로딩되는 컴포넌트가 거의 없습니다.글로벌 vue 변수와 vue commonents를 로드한 후 동적으로 jQuery를 사용하여 일부 컨테이너(#blog 등)의 lengight > 0이 되면 추가 vue commonents 스크립트를 로드합니다.

문제는 Vue가 Vue 태그를 찾았지만 구성 요소를 등록할 수 없다는 오류를 발생시키고 있다는 것입니다.

JS 파일을 동적으로 로드할 수 있는 방법이 있습니까?특정 서브페이지에만 로드하고 싶은 js파일이 많은 큰 웹사이트가 생겼습니다.모든 jQuery libs에서 완벽하게 작동하지만 Vue 구성 요소에서는 작동하지 않습니다.

다음 컴포넌트 예:

Vue.component('blog-entries', {
    name: "blog-entries",
    template: require('js/vue/home/blog/blog.html').template,
    data: function () {
        return {
            blog_entries: [

            ]
        }
    }
});

및 오류:

[Vue warn] :알 수 없는 사용자 지정 요소: - 구성 요소를 올바르게 등록했습니까?재귀 구성 요소의 경우 "이름" 옵션을 제공해야 합니다.

(에 기재되어 있습니다).

스크립트 로드:

function loadScript(scriptName, callback) {

    if (!_arr[scriptName]) {
        _arr[scriptName] = true;

        var body        = document.getElementsByTagName('body')[0];
        var script      = document.createElement('script');
        script.type     = 'text/javascript';
        script.src      = scriptName;

        // then bind the event to the callback function
        // there are several events for cross browser compatibility
        // script.onreadystatechange = callback;
        script.onload = callback;

        // fire the loading
        body.appendChild(script);

    } else if (callback) {

        callback();

    }

};

var vapp = new Vue({
  el: '#app',
  data: function() {
    return {
      componentName: ''
    }
  },
  computed: {
    currentComponent: function() {
      var vm = this;
      if (!vm.componentName) return;

      if (!vm.$options.components[vm.componentName] //if not registered locally
          && !Vue.options.components[vm.componentName]) {//nor globally yet

        //load the component async'ly
        Vue.component(vm.componentName, function(resolve) {
          //adjust the path to where your component files are
          var filePath = 'https://elfan.net/vue-components/' + vm.componentName + '.vue.js';
          loadScript(filePath, resolve);
        });
      }
      return vm.componentName;
    }
  }
});

/*below is your own third party script loader*/
var _arr = {};
function loadScript(scriptName, callback) {

    if (!_arr[scriptName]) {
        _arr[scriptName] = true;

        var body        = document.getElementsByTagName('body')[0];
        var script      = document.createElement('script');
        script.type     = 'text/javascript';
        script.src      = scriptName;

        // then bind the event to the callback function
        // there are several events for cross browser compatibility
        // script.onreadystatechange = callback;
        script.onload = callback;

        // fire the loading
        body.appendChild(script);

    } else if (callback) {

        callback();

    }

}
<!DOCTYPE html>
<html>
  <body>

    <div id="app">
      <input v-model="componentName">
      <div :is="currentComponent"></div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
    <script src="app.js"></script>

  </body>

</html>

메인 앱(서브 페이지를 로드하는 앱)에서 다음과 같이 시도합니다.

Vue.component('blog-entries', function(resolve) {
    loadScript('blog-entries.js', resolve);
})

여기서 'blog-entries'는 Vue 컴포넌트의 이름과 같아야 하며 'blog-entries.js'는 동적으로 로드할 Vue 컴포넌트가 들어 있는 js 파일입니다.

편집: 후속 조치를 위해 vue 컴포넌트를 동적으로 로드하기 위한 전체 코드를 여기에 입력합니다.사용자가 입력하는 즉시 컴포넌트가 로드되고 렌더링됩니다."개미", "새" 또는 "고양이"를 입력할 수 있습니다.이러한 이름의 vue 컴포넌트를 서버에 배치했습니다.

언급URL : https://stackoverflow.com/questions/45847237/vue-cannot-register-coponent-if-js-file-is-loaded-externally

반응형