Vue中$refs的理解 $refs是一个对象,持有注册过ref attribute的所有DOM元素和组件实例。 描述 ref被用来给元素或子组件注册引用信息,引用信息将会注册在父组件的$refs对象
Vue中$refs的理解
<!DOCTYPE html>
<html>
<head>
<title>Vue</title>
</head>
<body>
<div id="app">
<div ref="node">Node</div>
<layout-div ref="layout"></layout-div>
<div v-for="i in 3" :key="i" ref="nodearr">{{i}}</div>
</div>
</body>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.js"></script>
<script type="text/javascript">
Vue.component("layout-div",{
data: function(){
return {
count: 0
}
},template: `<div>
<div>{{count}}</div>
</div>`
})
var vm = new Vue({
el: '#app',mounted: function(){
console.log(this.$refs.node); // <div>Node</div> // DOM元素
console.log(this.$refs.layout); // VueComponent {_uid: 1,...} // 组件实例
console.log(this.$refs.nodearr); // (3) [div,div,div] // DOM元素数组
}
})
</script>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Vue</title>
</head>
<body>
<div id="app"></div>
</body>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.js"></script>
<script type="text/javascript">
var vm = new Vue({
el: '#app',data: function(){
return {
msg: 0
}
},template: `<div>
<div ref="node">{{msg}}</div>
<button @click="updateMsg">button</button>
</div>`,beforeMount: function(){
console.log(this.$refs.node); // undefined
},mounted: function(){
console.log(this.$refs.node); // <div>0</div>
},methods: {
updateMsg: function(){
this.msg = 1;
console.log(this.$refs.node.innerHTML); // 0
this.$nextTick(() => {
console.log(this.$refs.node.innerHTML); // 1
})
}
}
})
</script>
</html>
https://github.com/WindrunnerMax/EveryDay
https://cn.vuejs.org/v2/api/#ref
https://zhuanlan.zhihu.com/p/50638655
https://juejin.im/post/5da58c54e51d4524e207fb92