How to use ref attribute to retrieve object or component ?
Saturday 2nd of January 2021 09:00:42 AMVueJS
When we apply VueJS to an application, sometimes when we want to retrieve data from the original application into objects or components then we can assign the ref = "myname" property to the desired object or component. access is then accessed using the this. $ refs.myname property
User ref for object
<!DOCTYPE html>
<html>
<head>
<title>How to use ref attribute to retrieve object or component ? - HtmlcssDownload.com</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<div id="app">
<div ref="mywebsite"></div>
<button @click.stop.prevent="viewMySite()">View my site</button>
</div>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
},
methods:{
viewMySite: function(){
this.$refs.mywebsite.innerHTML = "HtmlcssDownload.com";
}
}
})
</script>
</body>
</html>
User ref for component
<!DOCTYPE html>
<html>
<head>
<title>How to use ref attribute to retrieve object or component ? - HtmlcssDownload.com</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<div id="app">
<mywebsite ref="mysite"></mywebsite>
<button @click.stop.prevent="viewMySite()">Click to change mysite</button>
</div>
<script type="text/javascript">
Vue.component('mywebsite',{
template: `<div>{{ mysitename }}</div>`,
data: function(){
return {
mysitename: '--'
}
}
})
var app = new Vue({
el: '#app',
data: {
},
methods:{
viewMySite: function(){
this.$refs.mysite.mysitename = "HtmlcssDownload.com";
}
}
})
</script>
</body>
</html>
We are Recommending you: