I have installed a npm package, however i am using the vue framework. The npm package is written in JS, but Vue's syntax is different that JS, even though it is a JS framework. How can i use the package in my vue project?
I have mainly installed the npm package and unsure how to translate what is written in it. i am new to coding and only recently learnt JS and now trying Vue
CodePudding user response:
The Vue syntax is still some standard JS, just with some added sugar, and as such, NPM packages can be imported inside your Vue components <script>
tag via a simple import.
For example:
import axios from 'axios';
export default {
...
methods: {
doSomething() {
axios.get(...)
}
}
}
Some packages might expose more defined methods and properties for you to import, in which case you can use what is called "destructuring" in order to import just what you need from the package as opposed to the whole package:
import { method_1, method_3, property_a } from 'myPackage';
export default {
data() {
return {
myComponentProperty: property_a
}
},
...
methods: {
doSomething() {
const a = 'something';
const b = method_1(a);
return b;
}
}
}
Generally speaking, just find your package on https://www.npmjs.com/ and look at the instructions to use it, you'll have some examples on how to import and use it in your project.
CodePudding user response:
Depends of the package you're using, if it's a simple date formater or if it's a whole calendar with baked-in features already.
The first one can be chained/nested into a method as explained here.
The other one is quite harder and more advanced, and will require the usage of methods linked below:
- if you want to achieve that in Nuxt (meta-framework mainly used with Vue for SSR): https://stackoverflow.com/a/68485267/8816585
- for Vue, I guess this is still the way to go: https://vuejs.org/guide/components/provide-inject.html#inject
This article is a bit old but still relevant as of how to abstract and plug some vanilla JS code to your VueJS instance. I'm sure you can find even more like this one.
Since you're new to JS/Vue, I recommend that you take things easy overall and use only the first type of packages that could be easily integrated.
Overall, get used to the whole ecosystem way of doing things.
An easy way is sometimes to prefix/suffix your package, for example swiper can also be used thanks to swiper/vue
.
You can find a nice list of cool packages here overall: https://github.com/vuejs/awesome-vue