在InertiaJS+Vue事件处理器中使用lodash _.pull函数报错求助
解决Vue模板中调用lodash _.pull报错的问题
问题原因
虽然你在bootstrap.js里把_挂载到了window全局对象,但Vue模板的表达式运行在组件渲染上下文(即_ctx)中,这个上下文不会自动注入window的全局变量。所以在模板的@click事件里直接写_.pull时,Vue会去组件上下文找_,而非window,导致找不到pull方法报错。
解决思路
1. 组件内显式引入lodash(推荐)
在组件的<script setup>里直接引入lodash(或单独引入pull),此时_会成为组件上下文的变量,模板可直接访问:
<script setup> // 全量引入(如果需要用多个lodash方法) import _ from 'lodash' // 或按需引入(更轻量化) // import { pull } from 'lodash' const array = ref(['a', 'b', 'c']) </script> <template> <!-- 全量引入时用_.pull --> <button @click="_.pull(array, 'a', 'c')">My button</button> <!-- 按需引入时直接用pull --> <!-- <button @click="pull(array, 'a', 'c')">My button</button> --> </template>
2. 挂载lodash到Vue全局属性
如果希望所有组件都能直接在模板里用_,可以在项目入口(比如app.js)把_挂载到Vue的全局属性上:
// app.js import _ from 'lodash' import { createApp } from 'vue' import { createInertiaApp } from '@inertiajs/vue3' createInertiaApp({ resolve: name => require(`./Pages/${name}.vue`), setup({ el, App, props, plugin }) { const app = createApp({ render: () => h(App, props) }) .use(plugin) // 挂载全局属性 .config.globalProperties._ = _ app.mount(el) }, })
之后所有组件的模板里都能直接使用_.pull等lodash方法。
3. 封装事件处理函数(最佳实践)
把lodash调用逻辑封装到组件的事件处理函数中,模板只负责绑定事件,更符合Vue的代码组织规范:
<script setup> import _ from 'lodash' const array = ref(['a', 'b', 'c']) const handleRemoveItems = () => { _.pull(array.value, 'a', 'c') } </script> <template> <button @click="handleRemoveItems">My button</button> </template>
内容的提问来源于stack exchange,提问作者andcl
相关产品推荐
相关产品推荐

