我想将在我的 vue.js/Webpack 中选择的 jQuery 插件与 TypeScript 应用程序一起使用。
我读到最好将插件包装在自定义 Vue 组件中。
我安装了 NPM 包:
npm install jquery --save
npm install @types/jquery --save
npm install chosen-js --save
npm install @types/chosen-js --save
我的组件:
<template>
<select>
<option value="1">Test1</option>
<option value="2">Test2</option>
</select>
</template>
<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";
import $ from 'jquery';
import 'chosen-js';
@Component
export default class ChosenSelect extends Vue{
@Prop()options!:string;
@Prop()value!:string;
mounted() {
let vm = this;
let el = $(vm.$el);
console.log(el);
}
}
</script>
没有 import 'chosen-js' jQuery 可以正常工作 - 当我在另一个组件中使用该组件时,我得到一个控制台输出。
使用 import 'chosen-js' 我只会从所选库中得到 Uncaught ReferenceError: jQuery is not defined
。
导入 jQuery 和 chosen-js 并在 vue Typescript 组件中使用它们的正确方法是什么。
最佳答案
感谢 https://medium.com/@NetanelBasal/typescript-integrate-jquery-plugin-in-your-project-e28c6887d8dc,我弄明白了
首先,安装jquery
npm install jquery --save
npm install @types/jquery --save
然后在您的任何组件中添加它。
import * as $ from 'jquery';
通过做这样的事情来检查 jquery 是否工作
import * as $ from 'jquery';
export default class Home extends Vue {
created () {
this.test()
}
test () {
console.log($('body')) // It's work
}
}
有时您需要等待加载 dom 才能执行 jquery 操作。
<template>
<div class="home">
<div id="test">wijfwoe</div>
</div>
</template>
<script>
import * as $ from 'jquery';
export default class Home extends Vue {
created () {
}
mounted () {
let a = $('#test')[0];
console.log(a.textContent);
}
</script>
关于javascript - Vue/Webpack/Typescript - 如何使用 jQuery 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52289828/