简体   繁体   English

在 app.js laravel 上创建全局方法 vue

[英]Create global method vue on app.js laravel

I want create global method to translate message using Laravel-JS-Localization我想创建使用Laravel-JS-Localization翻译消息的全局方法

But when i call the method using vue mustache got an error like this:但是当我使用 vue mustache 调用该方法时,出现如下错误:

Property or method "trans" is not defined on the instance but referenced during render.
Make sure that this property is reactive.

Here my laravel app.js code:这是我的 laravel app.js代码:

require('./bootstrap');

window.Vue = require('vue');

Vue.component('dashboard', require('./components/Dashboard').default);

const app = new Vue({
  el: '#vue',
  methods: {
    trans: function (key) {
      return Lang.get(key);
    },
  },
});

Dashboard.vue code: Dashboard.vue代码:

<template>
 <p>{{ trans('common.welcome') }}</p>
</template>

<script>
 data () {
  return {
   name: '',
  }
 },
</script>

dashboard.blade.php code: dashboard.blade.php代码:

..........

    <div class="col-9" id="vue">
     <dashboard></dashboard>
    </div> <!--c end col-8 -->

..........

I would probably go with creating a Plugin .我可能会 go 创建一个Plugin For example例如

Vue.use({
  install (Vue) {
    Vue.prototype.$trans = Lang.get
  }
})

Adding this to your app.js code before creating any components or new Vue({...}) will mean all your components will have access to the $trans method.在创建任何组件或new Vue({...})之前将其添加到您的app.js代码将意味着您的所有组件都可以访问$trans方法。


Alternatively, you can create a Global Mixin but these aren't strongly recommended.或者,您可以创建一个全局 Mixin ,但不强烈推荐这些。

Use global mixins sparsely and carefully, because it affects every single Vue instance created, including third party components谨慎使用全局 mixins,因为它会影响创建的每个 Vue 实例,包括第三方组件

Vue.mixin({
  methods: {
    trans (key) {
      return Lang.get(key)
    }
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM