2017-05-03 59 views
6

私は配列を持っている:配列内のオブジェクトを1つだけ見る方法は?

basicForm.schema = [ 
    {}, 
    {} // I want to watch only this 
] 

私はこれをやってみました:

‘basicForm.schema[1].value’: { 
    handler (schema) { 
    const plan = schema.find(field => { 
     return field.name === ‘plan’ 
    }) 
    }, 
    deep: true 
}, 

しかし、私はこのエラーを得た:

vue.js?3de6:573 [Vue warn]: Failed watching path: “basicForm.schema[1]” Watcher only accepts simple dot-delimited paths. For full control, use a function instead.

これを行うための正しい方法は何ですか?

答えて

5

することはでき代わりにwatchcomputed property:警告メッセージが示すとおり

new Vue({ 
 
    el: '#app', 
 
    data: { 
 
    basicForm: { 
 
     schema: [ 
 
     \t {a: 1},{b: 2} // I want to watch only this 
 
     ] 
 
    } 
 
    }, 
 
    computed: { 
 
    bToWatch: function() { 
 
     return this.basicForm.schema[1].b 
 
    } 
 
    }, 
 
    methods: { 
 
    incB: function() { 
 
     this.basicForm.schema[1].b++ 
 
    } 
 
    }, 
 
    watch: { 
 
    bToWatch: function(newVal, oldVal) { 
 
     console.log(newVal) 
 
    } 
 
    } 
 
});
<script src="https://unpkg.com/vue/dist/vue.js"></script> 
 

 
<div id="app"> 
 
    <button @click="incB()">Inc</button> 
 
</div>

3

あなたは機能を使用する必要があります。 vm.$watchでこれを行う必要があります。

new Vue({ 
 
    el: '#app', 
 
    
 
    data: { 
 
    items: [ 
 
     { name: 'bob' }, 
 
     { name: 'fred' }, 
 
     { name: 'sue' }, 
 
    ], 
 
    }, 
 
    
 
    created() { 
 
    this.$watch(() => this.items[1].name, this.onNameChanged); 
 
    }, 
 
    
 
    methods: { 
 
    changeValue() { 
 
     this.items[1].name = 'rose'; 
 
    }, 
 
    
 
    onNameChanged(name) { 
 
     alert('name changed to ' + name); 
 
    }, 
 
    }, 
 
});
<script src="https://unpkg.com/vue/dist/vue.js"></script> 
 

 
<div id="app"> 
 
    <button @click="changeValue">Click me</button> 
 
</div>

おそらくthis.items[1]がそうでなければ、あなたがエラーを取得します、時計機能の内部でそれにアクセスする前に存在していることを確認する必要があります。

関連する問題