【问题标题】:how to access refs in methods in vuejs如何在 vuejs 中的方法中访问 refs
【发布时间】:2019-07-21 00:18:36
【问题描述】:

我想在方法对象内的函数中访问模板引用。目前,它在访问 refs 时会抛出 undefined。

下面是我的代码:

<template>
    <ul ref="lvl1_target" style="width: 440px" class="lvl1_target milestone_asset_data">
        <li :style="{'width': getMileStonePercent(4,'lvl1_target')}" class="hybse_data">
            <span></span>
            <i></i>
            <small>$4M</small>
        </li>
    </ul>
</template>

我在脚本标签中的代码如下:

export default {
    methods: {
        getMileStonePercent(num, secWrp) {
            let ele = this.$refs[secWrp]
            return ele.offsetWidth + '%'
        },
    },
    created() {},
}

请提供解决方案,通过访问我的函数中的模板引用来获取宽度。提前致谢。

【问题讨论】:

    标签: vue.js reference vuejs2 vue-component ref


    【解决方案1】:

    您需要将ref 属性添加到您要定位的元素。

    我不太确定你到底想做什么,所以这里是一个通用示例:

    <template>
        <div ref="myElement"></div>
    </template>
    
    export default {
        methods: {
            setText() {
                this.$refs.myElement.innerHTML = "Hello world"
            },
        },
    }
    

    Vue ref documentation

    【讨论】:

    • 当我尝试访问 myElement 时抛出 undefined
    • 来自文档:$refs are only populated after the component has been rendered, and they are not reactive. It is only meant as an escape hatch for direct child manipulation - you should avoid accessing $refs from within templates or computed properties.
    • 您需要在mounted 回调中处理此问题。
    【解决方案2】:

    你可以试试

    export default {
      methods: {
        this.$next(tick() => {
          setText() {
            this.$refs.myElement.innerHTML = "Hello world"
        }
      })
    }}
    

    【讨论】:

      猜你喜欢
      • 2017-04-14
      • 2021-04-17
      • 2018-01-17
      • 2019-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 1970-01-01
      相关资源
      最近更新 更多