【问题标题】:Using Vue $refs dynamically inside of function with parameter在带参数的函数内部动态使用 Vue $refs
【发布时间】:2018-03-13 13:02:44
【问题描述】:

我正在尝试使用 $refs 功能通过 Vue 访问 DOM 元素,但我无法让它工作。

我的元素如下所示。 plateId 是动态生成的,所以不会一直是同一个数字:

<textarea :ref="plateId + '-notes'">

我的 Vue 函数如下所示:

/* This does not work */
addNotes: function(plateId) {
    console.log(this.$refs.plateId + '-notes');
}

每当我运行此代码并激活该功能时,它只会在我的控制台中读取undefined。我也试过这个,它也不起作用并且读取未定义:

/* This does not work */
addNotes: function(plateId) {
    var plateIdNotes = plateId + '-notes';
    console.log(this.$refs.plateIdNotes);
}

const替换var(我正在使用ES6并转译代码)也不起作用:

/* This does not work */
addNotes: function(plateId) {
    const plateIdNotes = plateId + '-notes';
    console.log(this.$refs.plateIdNotes);
}

我知道ref 正确绑定到元素,因为当我在下面执行此操作时,我可以在控制台中看到我的所有其他参考,以及 plateId-notes 参考:

/* This works */
addNotes: function(plateId) {
    console.log(this.$refs);
}

如何使用函数中的参数访问plateId ref?

【问题讨论】:

    标签: javascript function parameters vue.js ref


    【解决方案1】:

    您可以使用[] 表示法:

      methods: {
        foo (id) {
            alert(this.$refs[id + '-test'].innerText)
        }
      }
    

    一个完整的工作示例:https://jsfiddle.net/drufjsv3/2/

    【讨论】:

    • 此外,如果您在使用v-for 和动态refs 制作的一堆组件中使用它,您将需要使用this.$refs[id + '-test'][0].innerText 来访问该组件中的任何内容vuejs.org/v2/api/#ref
    【解决方案2】:

    此外,您可以通过访问

    访问视图中呈现的所有 $refs
    vm.$children.forEach( child => {
        var tag = child.$vnode.data.ref;
        console.log(vm.$refs[tag]);
        vm.$refs[tag].loadData();  
    });
    // loadData() is a method to implement when mounted or when you want to reload data
    

    //////////////////////////////

    <script>
        export default {
    
          data() {
            return {
                notifications: []
            }
        },
    
        mounted() {
            this.loadData();
        },
    
        methods: {
    
            loadData: function() {
                axios.get('/request-json/notifications').then(res => {
                    this.notifications = res.data;
                });
            },
    .....
    

    【讨论】:

      猜你喜欢
      • 2020-04-22
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多