Vuejs Input Binding Based on Computed Property

2019-06-02 05:16发布

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" class="container-fluid">
    <h2>Input Binding</h2>
    <p><b>First Name</b></p>
    <input type="text" v-model="value.first" placeholder="Enter first name" />
    <p style="margin-top:20px;"><b>Second Name</b></p>
    <input type="text" :v-model="lastName" placeholder="Enter last name" />
    <hr />
    <p>{{value.first}} {{value.second}}</p>
    <hr />
    <p>Value of computed property: {{lastName}}</p>
  </div>
  <script>  
   new Vue({
      el: '#app',
      data: function() {
        return {
          value: {
          first:'',
          second:''}
        }
      },
    computed: {
        // a computed getter
        lastName: function() {
            return 'value.second'
        } 
      }     
    });
  </script>
</body>
</html>

As you can see in the above code, I want the first field to be bound to value.first so I have chosen v-model="value.first". For the second field, I want the model binding to be decided by the value returned from computed property. Right now it's a simple example and there's only one returned value, i.e., value.second. But this will be decided on logic.

Right now when I try to do that binding, it doesn't return anything. Any help is greatly appreciated.

1条回答
爷的心禁止访问
2楼-- · 2019-06-02 05:29

You can make use of a computed setter as follows:

computed: {
    lastName: {
        get(){
            //perform your logic
            return 'value.second'
        },
        set(newValue){
            this.value.second = newValue;
        }

    } 
  }     

Now use this computed property as v-model in your template;

<input type="text" v-model="lastName" placeholder="Enter last name" />

Here is the fiddle

查看更多
登录 后发表回答