'Is it possible to access data / html context from root Vue 3 component
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...).
Solution 1:[1]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | tony19 |