如何在 vue.js 中加载页面或视图后触发点击事件?

遇到这样的情况:加载页面或视图后触发单击,并popup触发vue.js编辑数据表行。我找不到这么好的VUE方法,尽管下面的链接提到了一种方法,如下所示:


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);

},

我以类似的方式做了如下。包含错误try catch,尽管它很丑陋,因为在某些时候数据不存在。


edit: function (idx, row) {

    ... nore code here ...

    try {

        document.getElementById(row.id).click();  // row.id is dynamic or variable

    } catch (error) {

        // pass

    }

},


然而我的队友,一个 vue.js 爱好者,说这不是一个该死的 VUE 方式。现在做这样的事情的正确方法是什么?


Cats萌萌
浏览 57回答 3
3回答

互换的青春

向您的元素添加一个名为 like 的 ref myBtn:&nbsp; <div ref="myBtn" >some content</div>然后运行点击:&nbsp;this.$refs.myBtn.click()例子 :Vue.config.devtools = false;Vue.config.productionTip = false;new Vue({&nbsp; el: '#app',&nbsp; methods: {&nbsp; &nbsp; logOk() {&nbsp; &nbsp; &nbsp; console.log("OK OK")&nbsp; &nbsp; }&nbsp; },&nbsp; mounted() {&nbsp; &nbsp; this.$refs.okBtn.click()&nbsp; }})<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><div id="app" class="container">&nbsp; <button ref="okBtn" @click="logOk"> OK</button></div>

12345678_0001

只需选择您的元素并在MountedVue 应用程序的生命周期中触发 Click 事件mounted() {&nbsp;this.$nextTick(() => {&nbsp; &nbsp;document.getElementById('myBtn').click()&nbsp;});&nbsp; &nbsp; &nbsp;&nbsp;}$nextTick根据 VueJs 文档:推迟回调在下一个 DOM 更新周期后执行。更改一些数据后立即使用它以等待 DOM 更新

紫衣仙女

在您的示例代码中,不需要任何 DOM 操作。像 Vue 这样的声明式响应式框架的主要优势是将模型的更改自动传播到视图。只需通过v-model适当的设置即可选择适当的单选按钮。new Vue({&nbsp; el: '#app',&nbsp; data() {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; li_address: [{name: 'CA'}, {name: 'NY'}, {name: 'AL'}],&nbsp; &nbsp; &nbsp; name: 'NY'&nbsp; &nbsp; }&nbsp; }})<div id="app" class="container">&nbsp; <div class="uk-grid" uk-grid>&nbsp; &nbsp; <div v-for="r in li_address">&nbsp; &nbsp; &nbsp; <label :for="r.name">{{r.name}}&nbsp; &nbsp; &nbsp; <input type="radio" v-model="name" :id="r.name" :value="r.name">&nbsp; &nbsp; &nbsp; </label>&nbsp; &nbsp; </div>&nbsp; &nbsp; <h4>NAME: {{ name }}</h4>&nbsp;&nbsp; </div></div><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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript