【问题标题】:Vue <template> in a .vue file with Lodash带有 Lodash 的 .vue 文件中的 Vue <template>
【发布时间】:2025-12-16 20:25:01
【问题描述】:

在我的模板部分的 .vue 文件中,我有:

<a v-bind:href="'javascript:artist(\'' + _.escape(artist) + '\')'">

使用 Lodash 函数 _.escape。这会生成一串错误,其中第一个是:

[Vue warn]: Property or method "_" is not defined on the instance but referenced during 
render.

但是在组件脚本部分的同一个文件中,我很高兴并且成功地使用了一系列 Lodash 函数。

这是一个 Laravel 应用程序,在我的 app.js 文件中我有以下代码:

require('./bootstrap');

window.Vue = require('vue');
import VueRouter from 'vue-router';

window.Vue.use(VueRouter);

import lodash from 'lodash';
Object.defineProperty(Vue.prototype, '$lodash', { value: lodash });

import SearchHome from './components/search.vue';

const routes = [
{
    path: '/',
    components: {
        searchHome: SearchHome
    }
},

]

const router = new VueRouter({ routes })

const app = new Vue({ router }).$mount('#app')

谁能帮帮我?

【问题讨论】:

  • 我也试过
  • 对不起!我已经解决了。它当然应该是 $lodash.escape()。

标签: laravel-5 vuejs2 lodash


【解决方案1】:

尝试改用计算值。这将提高可读性。 避免在绑定中进行复杂的操作。

<a :href="artistLink">

在脚本中

import _ from 'lodash'

export default {
    computed: {
       artistLink () {
           return 'javascript:artist(\'' + _.escape(this.artist) + '\')'
       }
    }
}

【讨论】: