繁体   English   中英

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

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

我想创建使用Laravel-JS-Localization翻译消息的全局方法

但是当我使用 vue mustache 调用该方法时,出现如下错误:

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

这是我的 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代码:

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

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

dashboard.blade.php代码:

..........

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

..........

我可能会 go 创建一个Plugin 例如

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

在创建任何组件或new Vue({...})之前将其添加到您的app.js代码将意味着您的所有组件都可以访问$trans方法。


或者,您可以创建一个全局 Mixin ,但不强烈推荐这些。

谨慎使用全局 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