Vuejs Input Binding Based on Array of Computed Pro

2019-08-23 11:43发布

问题:

I have a scenario where I want the v-model binding of an Input field to be decided by the value returned by a computed property.

Please see the example below:

<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/vue@2.1.10/dist/vue.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />  
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div id="app">
    {{value}}
    <input type="text" v-model="myName.first">
    <input type="text" v-model="myName.second">
</div>
  <script>  
    new Vue({
        el:'#app',
        data:{
            value:{
                first: '',
                second: ''
            }
        },
        computed: {
            myName: {
                get(){
                    return {first:'this.value.first',second:'this.value.second'};  //this will actually come from an API
                },
                set(newValue){
                    this.value.first = newValue.second;
                    this.value.second = newValue.second;
                }
            } 
        }     
    });
  </script>
</body>
</html>

As you can see in the above code, I want the first field to be bound to value.first and second value to be bound to value.second. For both fields, I want the model binding to be decided by the value returned from computed property. Right now it's a simple example and there are only two returned value, i.e., value.first and value.second. But this will be decided on logic.

I feel I am not making use of get and set correctly. Really appreciate any help.

Note: I had a previous question on similar lines but it had only one value returned in computed property instead of an array/object. The answer provided worked great However, this time the challenge is that we have two values that need to be set. You can see that thread here: Vuejs Input Binding Based on Computed Property

回答1:

You can v-model directly to a computed property without using data or set/get.

CodePen

<input type="text" v-model="myName.first">

data:{},
computed: {
   myName: function() {
       return this.$store.state.myName; //or whatever your api is
   } 
}     

Also, make sure the value of your computed property is present before your input loads.