How to use external vue npm components

2019-08-10 22:52发布

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条回答
不美不萌又怎样
2楼-- · 2019-08-10 23:18

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.

查看更多
登录 后发表回答