【问题标题】:Cannot create new Instance Properties in Vue.js (laravel project)无法在 Vue.js(laravel 项目)中创建新的实例属性
【发布时间】:2021-08-17 14:45:37
【问题描述】:

我正在尝试创建本地化属性,例如 Laravel 刀片模板中的 __('text')。 我创建了一个全局窗口变量,它包含所有需要的数据,名称为 window.i18n

这是我的resourses/js/app.js 文件:

require('./bootstrap');

window.Vue = require('vue');

// Here I tried to create new Instance properties
import _ from 'lodash'
window.Vue.prototype.__ = str => _.get(window.i18n, str)

Vue.component('autocomplete',require('./components/SearchComponent.vue').default);

const app = new Vue({
    el: '#app',
});

还有我的/components/SearchComponent.vue 文件,只有脚本部分:

<script>
 export default{
    props: [
        'categories'
    ],
    data(){
        return {
            query: '',
            results: [],
            categoryText: __('text.save'), // Here I tried to use __() property
            categoryId: 0
        }
    },
    methods: {
    autoComplete() {
        this.results = [];
        if(this.query.length > 2){
            axios.get('/posts/search',{params: {query: this.query, category_id: this.categoryId}}).then(response => {
                this.results = response.data;
                this.categoryText = "Избери";
                this.categoryId = 0;
            });
        }
    },
    categoryChange(e) {
        this.categoryText = e.target.text;
        var id = event.target.getAttribute('data-category-id');
        this.categoryId = id;
    },
    mounted: function () {
        console.log(this.categories);
    }
    }
 }
</script>

我收到了这个错误:

app.js:38639 [Vue 警告]:data() 中的错误:“ReferenceError: __ is not 定义”

无法处理我缺少的东西。

【问题讨论】:

  • 你试过 window.__('text.save') 吗?
  • 您是否尝试使用 categoryText 作为计算属性? return this.__(‘text.save’)

标签: javascript laravel vue.js laravel-8


【解决方案1】:

您已将__ 添加到Vue.prototype,使其成为实例属性。要访问实例属性,请在 data() 中使用 this

export default {
  data() {
    return {         ?
      categoryText: this.__('text.save')
    }
  }
}

或者,您可以通过将__ 直接附加到window 来将其设为全局,这将使您当前的代码能够工作:

window.__ = str => _.get(window.i18n, str)

【讨论】:

  • 你应该知道这个解决方案不是被动的:切换语言不会自动更新categoryText。请改用vue-i18n,并将categoryText 移动到computed
猜你喜欢
  • 1970-01-01
  • 2016-06-09
  • 2020-04-12
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 2018-05-06
  • 2020-09-17
相关资源
最近更新 更多