簡體   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