[英]Vue/Webpack/Typescript - How to use jQuery Plugin
我想将在我的 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 正在工作 - 当我在另一个组件中使用该组件时,我得到一个控制台 output。
使用import 'chosen-js'我只得到Uncaught ReferenceError: jQuery is not defined
from the chosen library。
导入 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>
把它放在 main.ts 文件中,它将在组件内部可用。
declare global {
interface Window { $: any; }
}
window.$ = require('jquery')
我建议使用特定于Vue的选择插件,而不必依赖基于jQuery的插件,该插件在DOM操作方面有点违反了使用Vue之类的目的。 其中大多数已经引入了自己的组件,因此无需创建包装器。
这里维护着大量的Vue资源,而不仅仅是插件: awesome-vue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.