vue.js - $refs 在 vue js 中返回 undefined
问题描述
我在使用ref
标签的引用时遇到了困难,因为它当前返回null
。部分代码如下所示:
<input-layout v-if="edit" label="Status" class="" ref="statusSubtitle">
<u-select v-model='item.status' :options="adStatus" :disable="disable" tabindex="14" class="" ref="itemStatusDropDown"/>
</input-layout>
mounted () {
this.$nextTick(function (){
console.log("222 " + this.$refs.itemStatusDropDown)
console.log("333 ", this.$refs.statusSubtitle)
})
},
computed: {
edit () {
//return true
return this.item.getId() != null
},
}
目前,钩子内的 console.logs mounted
return undefined
。这里的问题是edit()
函数中的内容是异步的,因此在钩子被触发v-if="edit"
时仍然是错误的。mounted
我想为标签添加一个类属性<input-layout>
,<u-select>
因此我的思考过程是:
this.$refs.statusSubtitle.class.value = "makeItGray"
this.$refs.itemStatusDropDown.class.value = "makeItGray"
但是,因为this.$refs.statusSubtitle
并this.$refs.itemStatusDropDown
返回undefined
我无法添加类属性。
在这种情况下,如何向类属性添加值?也许有一个我没有想到的解决方法?
注意:如果我强制edit()
方法返回true
,则ref
不再是未定义的。但在这种情况下,该edit()
方法正在执行异步任务。
解决方案
对于这种情况,我会观察edit
计算结果。
Vue.config.devtools = false;
Vue.config.productionTip = false;
var app = new Vue({
el: '#app',
data: {
status: false
},
computed: {
edit() {
return this.status;
}
},
watch: {
edit: {
immediate: true,
handler() {
this.$nextTick(() => {
if (this.$refs.myRef) {
console.log(this.$refs.myRef);
this.$refs.myRef.style.backgroundColor = 'green'
}
})
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="status = !status">toggle</button>
<p v-if="edit" ref="myRef">{{ edit }}</p>
</div>
推荐阅读
- python - 如何在pygame的每个Tile网格中绘制数字?
- c# - 具有 Entity Framework Core 的 .NET 控制台应用程序:“进程没有包标识”仅在没有调试的情况下启动
- react-native - undefined 不是对象(评估“expoModule.Components.BlurView”)
- java - 在 Can Foundry PCF 中 manifest.yml 的 JAVA_OPTS 中配置 keystore
- javascript - TypeScript 在迭代中获取对象值
- python - 您如何创建一个函数来接收类别列表并计算每个类别中的元素数量?
- java - Telegram Bot gradle.build 配置
- azure - azure - powershell Set-AzVMDiagnosticsExtension 似乎无法跨订阅工作
- v8 - 如何在 V8 中使用嵌入式 JavaScript 管理关键资源
- reactjs - React Redux 和本地状态的最佳实践