首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >VueJS $watch $refs

VueJS $watch $refs
EN

Stack Overflow用户
提问于 2016-08-19 09:23:29
回答 5查看 61.1K关注 0票数 38

有可能去$watch Vue $refs

我希望针对嵌套在当前Vue实例中的子组件设置逻辑,但在ready回调中,$refs.childcomponent在处理时最初是undefined

ready()内部的

代码语言:javascript
复制
this.$watch('$refs', function() {
    console.log("not firing");
}, { deep: true });

结果:错误:超过最大调用堆栈

实例watch 属性

代码语言:javascript
复制
watch: {
  '$refs': {
     handler: function() { console.log("hit"); },
     deep: true
  }
}

结果:没什么。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2017-07-10 12:25:02

您可以使用$watch $refs.<name>.<data>,但不能使用$refs.<name>本身,更不用说$refs了。

https://jsfiddle.net/kenberkeley/9pn1uqam/

代码语言:javascript
复制
const Counter = {
  data: () => ({
    i: 0
  }),
  template: `<fieldset>
    <p>Counter</p>
    <code>i = {{ i }}</code>
    <button @click="i += 1"> Add One </button>
  </fieldset>`
}

const App = {
  components: { Counter },
  mounted () {
    this.$watch(
        () => {
            return this.$refs.counter.i
        },
      (val) => {
        alert('App $watch $refs.counter.i: ' + val)
      }
    )
  },
  template: `<fieldset>
    <p>App</p>
    <counter ref="counter" />
  </fieldset>`
}

new Vue({
    el: '#app',
    render: h => h(App)
})
票数 53
EN

Stack Overflow用户

发布于 2018-06-01 07:14:17

在以下安装使用代码中:

代码语言:javascript
复制
this.$watch(
        () => {
            return this.$refs.<name>.<data>
        },
      (val) => {
        alert('$watch $refs.<name>.<data>: ' + val)
      }
    )
票数 3
EN

Stack Overflow用户

发布于 2020-10-26 21:22:12

这方面有一项工作要做。考虑到当将数组赋值给变量时,JavaScript没有创建数组的副本,它只是创建了对原始数组的引用。知道Vue的$refs是数组,我们可以执行以下操作:

代码语言:javascript
复制
<template>
    <div>
            <ul v-if="showAvailable">
                 <li v-for="pet in allPets.available" :key="pet.id" ref="pets">
                      {{ pet.name }}
                 </li>
            </ul>
            <ul v-else>
                 <li v-for="pet in allPets.unavailable" :key="pet.id" ref="pets">
                      {{ pet.name }}
                 </li>
            </ul>
    </div>
</template>

<script>

export default {
    props: ['allPets'],

    data() {
         showAvailable: true // Normally would change from a button or something
         shownPets: null // set to null for now
    },

    mounted() {
         this.$set(this.$data, 'shownPets', this.$refs.pets);    
    },

    watch: {
         shownPets: {
                         handler(newVal, oldVal){
                              // Do something when the DOM changes!
                         },
                         deep: true
                    }
    }
}
</script>

还有哇哦。在组件挂载后,我们将数据shownPets设置为pets $ref。根据showAvailabletrue还是false,引用将包含不同的元素,现在我们可以查看$ref或DOM的更改。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39035498

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档