我刚刚开始使用Vue.js,并使用Vue CLI3创建了一个项目。目标是最终将我当前的应用程序迁移到Vue。我正在试验jQuery和Select2,因为这是在我当前的应用程序中使用的,我想知道这种方法是否正确,为什么我仍然会收到编译错误,即使它看起来很有效。注意:我确实通过Vue UI安装了jQuery依赖项。
以下是我所拥有的:
main.js
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 -视图
<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组件
<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中
"globals": {
"jQuery": true,
"$": true,
"global": true,
"window": true,
"document": true,
"process": true,
"module": true,
"console": true,
"sessionStorage": true,
"localStorage": true
}问题:
请帮帮我!非常感谢你们!
更新:
我将$(“#select2-test”).select2()移到组件中,并在挂载时启动它。在清理了我的VSCode设置并重新启动之后,我不再收到任何错误了。不过,如果这是正确的做法,我想得到一个意见。
<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>发布于 2019-02-13 23:32:16
通常,使用ref来获取元素,而不是依赖于jQuery或getElementById。
<select ref="theSelect" class="form-control" style="width: 50%">mounted() {
$(this.$refs.theSelect).select2();
}您还可能希望将select的值绑定到数据成员。
<select v-model='theValue' ref="theSelect" class="form-control" style="width: 50%">然后将theValue添加到数据选项中。然后,您可以使用this.theValue获取和设置select的值。您还可以对其进行watch并对更改作出反应。
最后,依赖于Vue的任何其他theValue计算属性或指令都将根据需要重新计算。
https://stackoverflow.com/questions/54678649
复制相似问题