登录/注册
小开开
2649
占位
2
占位
0
浏览量
占位
粉丝
占位
关注
Vue项目中npm安装 zTree
小开开
2020-10-10 16:02:09 2020-10-10
1172
0

简介

zTree 是一个依靠 jQuery 实现的多功能 “树插件”。优异的性能、灵活的配置、多种功能的组合是 zTree 最大优点。

安装

ztree安装

npm install ztree
yarn add ztree

由于 ztree 依赖 jQuery ,所以要安装 jQuery框架。

jQuery 安装

npm install jquery 
yarn add jquery

引入

在 main.js中引入插件

import $ from "jquery";
import "ztree";
import 'ztree/css/zTreeStyle/zTreeStyle.css';

遇到问题

项目启动后出现错误:jQuery is not defined
163756435e9c12f6e1869403.jpg

因为以前使用 <script> 标签来加载 jquery 的,并且会将其挂载到全局中,所以在执行 jquery.ztree.core.js 时能正常地获取到 jQuery 。而在 vue 项目中,经过 webpack 打包后,在 main.js 中导入的 $ 和 jquery.ztree.core.js 是各自处在不同的上下文环境的,所以就不能找到 jQuery 了

修改 webpack 配置

创建 vue.config.js 配置文件

// vue.config.js
const webpack = require('webpack')
module.exports = {
configureWebpack: {
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jquery: 'jquery',
'window.jQuery': 'jquery',
jQuery: 'jquery'
})
]
},
}

上面代码使用了 webpack 的 ProvidePlugin 插件,这个插件在加载某个模块时,如果遇到了未定义的并且在配置文件中配置了的变量,比如上面代码看到的 $、jquery、jQuery、window.jQuery,就会自动导入对应的依赖项,比如上面代码中的 jquery 模块。

同时,也不需要再在 main.js 中引入jquery 了。
重新启动项目后,jQuery is not defined 错误消失。

遇到新的问题

写个demo运行后,编译出错:'$' is not defined

163756436d0ad74c703bacf3.jpg

这是 eslint 的 no-undef 规则导致的,这条规则禁用未声明的变量

修改 eslint 配置

找到 .eslintrc.js 文件,在 env 选项中添加 jquery:true。

// .eslintrc.js
module.exports = {
env: {
jquery: true
}
}

env 选项定义了预定义的全局变量,添加了上述代码,那么 eslint 就会认为 jquery 是全局变量而不是一个未定义的变量了。

再次重新启动项目,就可以看到正常加载的 zTree 树形组件了

暂无评论