Ran into a case to trigger a click once a page or view is loaded, and a popup is triggered in vue.js to edit data table row. There is no such a good VUE way that I can find, although the following link mentioned a way as the follows:
https://forum.vuejs.org/t/how-to-trigger-a-click-event-through-code-in-vuejs-on-page-load/92582
mounted: function () {
setTimeout(function(){
const elem = document.getElementById('myBtn');
elem.click();
}, 100);
},
I did in a similar way as the follows. The try catch to contain error although it's ugly, since at some point the data doesn't exist.
edit: function (idx, row) {
... nore code here ...
try {
document.getElementById(row.id).click(); // row.id is dynamic or variable
} catch (error) {
// pass
}
},
However my team mate, a vue.js lover, said it's not a damn VUE way. Now what it the right way to do such a thing?
The following Demo is possible for the expected work:
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
el: '#app',
data: {
li_address: [{name: 'CA'}, {name: 'NY'}, {name: 'AL'}],
name: 'NY'
},
methods: {
},
mounted() {
console.log(['this.name', this.name]);
// this.$refs[this.name].click(); // failed
document.getElementById(this.name).click(); // worked. the click is triggered upon this.name
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/2.27.5/css/uikit.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/2.27.5/js/uikit.min.js"></script>
<div id="app" class="container">
<div class="uk-grid" uk-grid>
<div v-for="r in li_address">
<label>{{r.name}}
<input :id="r.name" :ref="r.name" type="radio" class="uk-radio" :value="r"
name="address_group">
</label>
</div>
</div>
</div>