ref的使用还是比较简单的,就是在Vue中可以操作DOM
分为以下两种情况:
1.通过ref操作html标签
下面的代码中,会打印"refP"
<div id="app">
<button @click="getRef()">获取标签ref</button>
<p ref="refP">refP</p>
</div>
<script>
const app = new Vue({
el: ‘#app‘,
data() {
return {
}
},
methods: {
getRef: function() {
console.log(app.$refs.refP.innerHTML);
},
},
})
</script>
2.通过ref操作组件
下面的代码中,会打印“组件Ref"
<div id="app">
<button @click="getRef2">获取组件ref</button>
<test-ref ref="refCom">refCom</test-ref>
</div>
<script>
Vue.component(‘test-ref‘, {
template: `<div><div>componentRef</div><div>{{test}}</div></div>`,
data() {
return {
test: ‘组件Ref‘
}
}
})
const app = new Vue({
el: ‘#app‘,
methods: {
getRef2: function() {
console.log(app.$refs.refCom.test);
}
},
components: {
testref: ‘test-ref‘
}
})
</script>
原文:https://www.cnblogs.com/jnuallen/p/15022138.html