ref is a very convenient attribute provided by vue. It can directly get the DOM node of the page element , or it can get the child component object .
Although Vue recommends not to manipulate the DOM in a vue project casually , in some last resort, the DOM must be manipulated . The ref attribute can easily achieve our needs.
Also, when we use subcomponents , we really want to get its data data and call its methods . This is also a great use of ref attributes .
In summary, it is very convenient and easy to use .
<div id="app">
<App></App>
</div>
<script>
Vue.component('Test',{
data () {
return {
msg:'Ray'
}
},
template:`
<div>
<h3>{
{msg}}</h3>
</div>
`
})
const App = {
data () {
return {
}
},
mounted () {
console.log(this.$refs.btn);
console.log(this.$refs.input);
// 加载页面,自动获取焦点
this.$refs.input.focus();
console.log(this.$refs.test);
},
components: {
},
template:`
<div>
<Test ref='test'></Test>
<input type='text' ref='input' />
<button ref='btn'>button</button>
</div>
`
}
new Vue({
el:'#app',
data:{
},
components: {
App
}
});
</script>
We wrote a global component Test , which is a simple h3 tag to display data data.
Then we wrote a partial component App , called the Test component, and gave it the ref attribute as test. We also wrote an input , a button , and ref attributes .
Finally, in the life cycle function of mounted , use the form of this.$refs to see what the ref attribute can get.
The first is to output this.$refs.btn and this.$refs.input respectively , which are the DOM nodes of this component element .
And we call focus function input elements , so that the input box to achieve the function automatically get the focus after loading , which shows that we really get to the true DOM node.
Then we look at the output of the sub-components of the this. $ Refs.test , successfully get to the child component object .
And try to call the data this.$refs.test.msg inside the component , and successfully get the data data inside the subcomponent .
The function of the ref attribute can be simply summarized into two points:
- Get the DOM node of this component element
- Get all the contents of the child component object
ref is a very, very useful attribute, get it quickly.
There is a WeChat mini program course design, complete design needs, contact personal QQ: 505417246
Pay attention to the following WeChat public account, you can receive WeChat applet, Vue, TypeScript, front-end, uni-app, full stack, Nodejs, Python and other practical learning materials. The
latest and most complete front-end knowledge summary and project source code will be released to the WeChat public as soon as possible No., please pay attention, thank you!