最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to watch only one object in an array? - Stack Overflow

programmeradmin0浏览0评论

I have an array:

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

I tried doing this:

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

But I got this error:

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.

What's the correct way of doing this?

I have an array:

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

I tried doing this:

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

But I got this error:

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.

What's the correct way of doing this?

Share Improve this question asked May 3, 2017 at 3:28 alexalex 7,60115 gold badges53 silver badges79 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 15

You can watch a computed property instead:

new Vue({
  el: '#app',
  data: {
    basicForm: {
      schema: [
      	{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>

You should use a function as the warning message suggests. You need to do so via 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>

You should probably check that this.items[1] exists before accessing it inside the watch function otherwise you'll get an error.

发布评论

评论列表(0)

  1. 暂无评论