Reputation: 19969
I have used Vue in the past but am struggling with how to pass information / args to a root Vue 3 component. In my html, I'd like to have something like this:
<div class="nav-app" nav="some-nav-jht"></div>
where in my mounted()
, I could access nav
via something like this:
mounted(){
console.log('here is nav: ' + this.nav);
How would I do this? I am doing this by loading Vue off of CDN (no webpack etc...).
Upvotes: 1
Views: 909
Reputation: 138676
As pointed out in comments, template refs enable accessing an element from <script>
.
Apply the ref
attribute to the element with a name (e.g., "navapp"
):
<div id="app"> 👇
<div class="nav-app" nav="some-nav-jht" ref="navapp">⋯</div>
</div>
Then in your mounted
hook, access the ref via this.$refs.REFNAME
:
<script>
Vue.createApp({
mounted() {
const navapp = this.$refs.navapp
console.log('here is nav: ' + navapp.getAttribute('nav'))
}
}).mount('#app')
</script>
Vue.createApp({
mounted() {
const navapp = this.$refs.navapp
console.log('here is nav: ' + navapp.getAttribute('nav'))
}
}).mount('#app')
<script src="https://unpkg.com/[email protected]/dist/vue.global.prod.js"></script>
<div id="app">
<div ref="navapp" nav="some-nav-jht">Hello world</div>
</div>
Upvotes: 3