How to use external vue npm components

天涯浪子 提交于 2019-12-11 13:30:21

问题


I am new to Vue.js, and am currently trying to use it in an existing solution. It is not possible for me to use .vue files. It's a standalone system, not using webpack. I need the files locally to make it work. In the example below, I have used .js's online.

I want to use this datepicker: https://github.com/mengxiong10/vue2-datepicker

My problem is that the datepicker isn't rendered.

I don't know how to register the component. I have tried to isolate what I want to do in a simple standalone example below.

I want to understand, how to register the external component. I have tried a lot of methods, and needs a helping hand. I hope someone out there have the knowledge and time to help me out.

Thanks in advance!

Here is what I do:

<!DOCTYPE html>
<html>
<head>
    <title>Vue test</title>
</head>
<body>

<script src="https://vuejs.org/js/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue2-datepicker"></script>

<div id="app">
    <input type="text" v-model="Data.SomeText" />
    <date-picker v-model="Data.SomeDate"></date-picker>
</div>

<script>
    var vm = new Vue({
        el: '#app',
        data: { Data: '' },
        components: {
            'date-picker': DatePicker
        },
        created: function () {
            this.Data = {"SomeText":"Hey","SomeDate":"2017-12-24T00:00:00"};
        }
    });
</script>

</body>
</html>

回答1:


The vue2-datepicker script is wrapped in a CommonJS module, which has a default export. In order to access it you have to specify you are accesing the default export:

components: {
  'date-picker': DatePicker.default
},

Working demo:

var vm = new Vue({
  el: '#app',
  data: {
    Data: ''
  },
  components: {
    'date-picker': DatePicker.default
  },
  created: function() {
    this.Data = {
      "SomeText": "Hey",
      "SomeDate": "2017-12-24T00:00:00"
    };
  }
});
<script src="https://unpkg.com/vue@2.5.13/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue2-datepicker"></script>

<body>
  <div id="app">
    <date-picker v-model="Data.SomeDate"></date-picker>
  </div>
</body>

As a sidenote, consider starting to develop with the webpack environment (you can use ready to use templates: https://github.com/vuejs-templates/webpack-simple). It takes effort initially to learn npm and some command line usage, but it is worth it in the long run: it will allow you to use Single File Components, easier plugin importing (some plugins may not be prepared to be included via <script> as it is the one you are using) and other advantages.



来源:https://stackoverflow.com/questions/48141191/how-to-use-external-vue-npm-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!