Can I pass parameters in computed properties in Vue.Js

前端 未结 10 1261
借酒劲吻你
借酒劲吻你 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.

    
    

    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.

    
    
    

提交回复
热议问题