Can I pass parameters in computed properties in Vue.Js

前端 未结 10 1219
借酒劲吻你
借酒劲吻你 2020-11-27 10:38

is this possible to pass parameter in computed properties in Vue.Js. I can see when having getters/setter using computed, they can take a parameter and assign it to a variab

相关标签:
10条回答
  • 2020-11-27 10:47

    You can pass parameters but either it is not a vue.js way or the way you are doing is wrong.

    However there are cases when you need to do so.I am going to show you a simple example passing value to computed property using getter and setter.

    <template>
        <div>
            Your name is {{get_name}} <!-- John Doe at the beginning -->
            <button @click="name = 'Roland'">Change it</button>
        </div>
    </template>
    

    And the script

    export default {
        data: () => ({
            name: 'John Doe'
        }),
        computed:{
            get_name: {
                get () {
                    return this.name
                },
                set (new_name) {
                    this.name = new_name
                }
            },
        }    
    }
    

    When the button clicked we are passing to computed property the name 'Roland' and in set() we are changing the name from 'John Doe' to 'Roland'.

    Below there is a common use case when computed is used with getter and setter. Say you have the follow vuex store:

    export default new Vuex.Store({
      state: {
        name: 'John Doe'
      },
      getters: {
        get_name: state => state.name
      },
      mutations: {
        set_name: (state, payload) => state.name = payload
      },
    })
    

    And in your component you want to add v-model to an input but using the vuex store.

    <template>
        <div>
            <input type="text" v-model="get_name">
            {{get_name}}
        </div>
    </template>
    <script>
    export default {
        computed:{
            get_name: {
                get () {
                    return this.$store.getters.get_name
                },
                set (new_name) {
                    this.$store.commit('set_name', new_name)
                }
            },
        }    
    }
    </script>
    
    0 讨论(0)
  • 2020-11-27 10:51

    You can also pass arguments to getters by returning a function. This is particularly useful when you want to query an array in the store:

    getters: {
      // ...
      getTodoById: (state) => (id) => {
        return state.todos.find(todo => todo.id === id)
      }
    }
    store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
    

    Note that getters accessed via methods will run each time you call them, and the result is not cached.

    That is called Method-Style Access and it is documented on the Vue.js docs.

    0 讨论(0)
  • 2020-11-27 10:57

    Computed could be consider has a function. So for an exemple on valdiation you could clearly do something like :

        methods: {
            validation(attr){
                switch(attr) {
                    case 'email':
                        const re = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
                        return re.test(this.form.email);
                    case 'password':
                        return this.form.password.length > 4
                }
            },
            ...
        }
    

    Which you'll be using like :

      <b-form-input
                id="email"
                v-model="form.email"
                type="email"
                :state="validation('email')"
                required
                placeholder="Enter email"
        ></b-form-input>
    

    Just keep in mind that you will still miss the caching specific to computed.

    0 讨论(0)
  • 2020-11-27 11:00

    Yes methods are there for using params. Like answers stated above, in your example it's best to use methods since execution is very light.

    Only for reference, in a situation where the method is complex and cost is high, you can cache the results like so:

    data() {
        return {
            fullNameCache:{}
        };
    }
    
    methods: {
        fullName(salut) {
            if (!this.fullNameCache[salut]) {
                this.fullNameCache[salut] = salut + ' ' + this.firstName + ' ' + this.lastName;
            }
            return this.fullNameCache[salut];
        }
    }
    

    note: When using this, watchout for memory if dealing with thousands

    0 讨论(0)
提交回复
热议问题