首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Vue CLI3 - jQuery和Select2 -编译错误

Vue CLI3 - jQuery和Select2 -编译错误
EN

Stack Overflow用户
提问于 2019-02-13 20:10:11
回答 1查看 602关注 0票数 0

我刚刚开始使用Vue.js,并使用Vue CLI3创建了一个项目。目标是最终将我当前的应用程序迁移到Vue。我正在试验jQuery和Select2,因为这是在我当前的应用程序中使用的,我想知道这种方法是否正确,为什么我仍然会收到编译错误,即使它看起来很有效。注意:我确实通过Vue UI安装了jQuery依赖项。

以下是我所拥有的:

main.js

代码语言:javascript
复制
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

/* Custom */
import "./js/jquery.js";
import "./js/select2.js";
import "./css/select2.css";

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");

$("#select2-test").select2();

Home.vue -视图

代码语言:javascript
复制
<template>
  <select2_test></select2_test>
</template>

<script>
// @ is an alias to /src
import select2_test from "@/components/select2_test.vue";

export default {
  name: "home",
  components: {
    select2_test
  }
};
</script>

select2_test.vue组件

代码语言:javascript
复制
<template>
  <div>
    <select id="select2-test" class="form-control" style="width: 50%">
      <option value="AK">Alaska</option>
      <option value="HI">Hawaii</option>
    </select>
  </div>
</template>

<script>
export default {
  name: "select2_test"
};
</script>

添加到.eslintrc.js中

代码语言:javascript
复制
"globals": {
"jQuery": true,
"$": true,
"global": true,
"window": true,
"document": true,
"process": true,
"module": true,
"console": true,
"sessionStorage": true,
"localStorage": true
}

问题:

  1. 这个方法正确吗?
  2. 为什么我会收到编译错误?: 模块警告(来自./node_node/eslint-加载程序/index.js):错误:src/main.js中没有定义'$‘(no-undef),在src/main.js: 19 :1: 17 \x}.$mount(“#app”);18欧元/19(“#select2 2-test”).select2();

请帮帮我!非常感谢你们!

更新:

我将$(“#select2-test”).select2()移到组件中,并在挂载时启动它。在清理了我的VSCode设置并重新启动之后,我不再收到任何错误了。不过,如果这是正确的做法,我想得到一个意见。

代码语言:javascript
复制
<template>
  <div>
    <select id="select2-test" class="form-control" style="width: 50%">
      <option value="AK">Alaska</option>
      <option value="HI">Hawaii</option>
    </select>
  </div>
</template>

<script>
export default {
  name: "select2_test",
  mounted() {
    $("#select2-test").select2();
  }
};
</script>
EN

回答 1

Stack Overflow用户

发布于 2019-02-13 23:32:16

通常,使用ref来获取元素,而不是依赖于jQuery或getElementById。

代码语言:javascript
复制
  <select ref="theSelect" class="form-control" style="width: 50%">
代码语言:javascript
复制
mounted() {
    $(this.$refs.theSelect).select2();
  }

您还可能希望将select的值绑定到数据成员。

代码语言:javascript
复制
  <select v-model='theValue' ref="theSelect" class="form-control" style="width: 50%">

然后将theValue添加到数据选项中。然后,您可以使用this.theValue获取和设置select的值。您还可以对其进行watch并对更改作出反应。

最后,依赖于Vue的任何其他theValue计算属性或指令都将根据需要重新计算。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54678649

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档