最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using global helper function in VueJS - Stack Overflow

programmeradmin5浏览0评论

I have small functions which needs to be used in many ponents. These functions just do some calculations on data and return, and are independent of rest of app. Should I put these functions in JS file at home directory or is there a Vue way to do this thing?

I have small functions which needs to be used in many ponents. These functions just do some calculations on data and return, and are independent of rest of app. Should I put these functions in JS file at home directory or is there a Vue way to do this thing?

Share Improve this question asked Nov 29, 2018 at 11:52 Shubham ChaudharyShubham Chaudhary 1,4824 gold badges20 silver badges38 bronze badges 1
  • @AhmedHammad Shouldn't Vuex be used only for state management? The functions I am talking about are just helper functions. – Shubham Chaudhary Commented Nov 29, 2018 at 12:04
Add a ment  | 

2 Answers 2

Reset to default 4

You can define your functions inside a global js file (for exemple 'functions.js'), or define them inside the main Vue's methods property:

// functions.js
export function message(value) {
  return 'hello ' + value
}

// and/or

// main.js
new Vue({
  el: "#app",
  ponents: { App },
  template: "<App/>",
  methods: {
    superMessage(value) {
      return 'super hello ' + value 
    }
  }
});

Then use these functions inside any ponent:

<template>
  <div>
    <p>{{ message('world') }}</p> <!-- "hello world" -->
    <p>{{ $root.superMessage('world') }}</p> <!-- "super hello world" -->
  </div>
</template>

<script>
import { message } from "./functions"
export default {
  methods: {
    message
  }
};
</script>

You could put these functions in the global JS file, but here are a few alternatives.

  1. Define the function as a method of the parent Vue ponent, and you can access it via this.$parent.method();.
  2. You could use a Vuex store, which will definitely be easier if you have a lot of nested child ponents accessing the method.

    state: {
        data: 'hi',
    },
    getters: {
        data(state){
            return Array.from(state.data).reverse().join('');
        }
    }
    
发布评论

评论列表(0)

  1. 暂无评论