鍍金池/ 問答/HTML/ VUE 中的$refs 貌似不能用于計(jì)算屬性中 是不是這樣的?

VUE 中的$refs 貌似不能用于計(jì)算屬性中 是不是這樣的?

js:

data: { usr: '' }
methods: {
        upper: function(ev){
             this.usr = this.$refs.name.value.toUpperCase(); // it's OK
        }
    },
     computed: {
         usr: function(ev){
            return this.$refs.name.value.toUpperCase();    //got error: TypeError: undefined is not an object (evaluating 'this.$refs.name.value') 
         }
    }

html:

        <input type="text" ref="name" v-model="usr" @keyup.enter="upper"><span>{{usr}}</span>
回答
編輯回答
悶油瓶

https://cn.vuejs.org/v2/guide... 文檔里面有重點(diǎn)指出的

$refs 只在組件渲染完成后才填充,并且它是非響應(yīng)式的。它僅僅是一個(gè)直接操作子組件的應(yīng)急方案——應(yīng)當(dāng)避免在模板或計(jì)算屬性中使用 $refs。

做了一個(gè)LC的測(cè)試來驗(yàn)證一下

    beforeCreate: function(){
        console.log("beforeCreate");
        console.log(this.$refs.name.value.length);
    },
    created: function(){
        console.log("created");
        console.log(this.$refs.name.value.length);
    },
    beforeMount: function(){
        console.log("beforeMount");
        console.log(this.$refs.name.value.length);
    },
    mounted: function(){
        console.log("mounted");
        console.log(this.$refs.name.value.length); //只有到了這里才有
    },
    beforeUpdate: function(){
        console.log("beforeUpdate");
        console.log(this.$refs.name.value.length);
    },
    updated: function(){
        console.log("updated");
        console.log(this.$refs.name.value.length);
    },
2018年9月2日 18:15
編輯回答
雨蝶

加一下空值判斷

computed: {
         usr: function(ev){
            return this.$refs.name ? this.$refs.name.value.toUpperCase() : '';
         }
    }
2017年7月28日 13:43
編輯回答
脾氣硬

報(bào)錯(cuò)原因是:

  1. 計(jì)算屬性在created階段之后mounted之前執(zhí)行。
  2. $refs的項(xiàng)在mounted之后才存在。

所以會(huì)報(bào)undefined的錯(cuò)。

2018年9月14日 14:32
編輯回答
淺淺

計(jì)算屬性不是這么玩兒的,并不是里面不能使用$refs,只是它的觸發(fā)機(jī)制和實(shí)際用途限制了如此做法是觸發(fā)不了計(jì)算屬性的,你可以在里面console.log隨便一個(gè)數(shù)試試。

我利用watch寫了一個(gè)達(dá)到你那個(gè)目的的功能,希望能對(duì)你有所幫助!

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>example</title>
</head>
<body>
    <div id="app">
        <input type="text" v-model="usr"><span>{{usr}}</span>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script type="text/javascript">
        new Vue({
            el: "#app",
            data: {
                usr: '11'
            },
            watch: {
                usr: function(val) {
                    return this.usr = val.toUpperCase();
                }
            }
        })
    </script>
</body>
</html>
2018年7月7日 12:20