简体   繁体   English

基于计算属性数组的Vuejs输入绑定

[英]Vuejs Input Binding Based on Array of Computed Properties

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. 我有一种情况,我希望输入字段的v模型绑定由计算属性返回的值决定。

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. 如您在上面的代码中看到的,我希望第一个字段绑定到value.first,第二个值绑定到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, ie, value.first and value.second. 现在这是一个简单的示例,只有两个返回值,即value.first和value.second。 But this will be decided on logic. 但这将取决于逻辑。

I feel I am not making use of get and set correctly. 我觉得我没有正确使用get和set。 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 您可以在此处看到该线程: 基于Compute属性的Vuejs输入绑定

You can v-model directly to a computed property without using data or set/get. 您可以直接对已计算的属性进行v建模,而无需使用数据或设置/获取。

CodePen 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. 另外,请确保在加载输入之前已存在计算属性的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM