Binding method result to v-model with Vue.js

别说谁变了你拦得住时间么 提交于 2021-02-18 19:49:38

问题


How do you bind a method result to a v-model with Vue.js?

example :

<someTag v-model="method_name(data_attribute)"></someTag>

I can't make it work for some reason.

Thank you.


回答1:


v-model expressions must have a get and set function. For most variables this is pretty straight forward but you can also use a computed property to define them yourself like so:

data:function(){
    return { value: 5 }
},
computed: {
    doubleValue: {
        get(){
            //this function will determine what is displayed in the input
            return this.value*2;
        },
        set(newVal){
            //this function will run whenever the input changes
            this.value = newVal/2;
        }
    }
}

Then you can use <input v-model="doubleValue"></input>

if you just want the tag to display a method result, use <tag>{{method_name(data_attribute)}}</tag>




回答2:


Years later, with more experience, I found out that is it easier to bind :value instead of using v-model. Then you can handle the update by catching @change.




回答3:


Agree with the :value and @change combination greenymaster. Even when we split the computed property in get/set, which is help, it seems very complicated to make it work if you require a parameter when you call for get(). My example is a medium sized dynamic object list, that populates a complex list of inputs, so:

  • I can't put a watch easily on a child element, unless I watch the entire parent list with deep, but it would require more complex function to determine which of the innter props and/or lists changed and do what fromthere
  • I can't use directly a method with v-model, since, it works for providing a 'get(param)' method (so to speak), but it does not have a 'set()' one
  • And the splitting of a computed property, have the same problem but inverse, having a 'set()' but not a 'get(param)'


来源:https://stackoverflow.com/questions/35210901/binding-method-result-to-v-model-with-vue-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!