javascript - v-on :click does not work (vue. js)

标签 javascript html vue.js

我尝试进入 vue.js 但我被卡住了。

HTML 页面:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script src="test.js"></script>
</head>
<body>
    <div id="app">
        <button v-on:click="exampleFunction">General</button>
    </div>
</body>
</html>

测试.js

var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  },
   created: function () {
       console.log('Vue instance was created');
   },
   methods:  {
       exampleFunction: function () {
           console.log('This is an example function');
       }
   },
   destroyed: function () {
       console.log('Vue instance was destroyed');
   }
})

app.exampleFunction();

控制台输出:

Vue instance was created
This is an example function

问题是该按钮不起作用,当我单击时它在控制台上什么也不写。

有什么建议吗?

最佳答案

它在片段中工作得很好。您可能想将 Vue 调用包装在 DOMContentLoaded 中确保在 Vue 尝试附加 DOM 之前 DOM 就在那里,就像我在下面所做的那样。

document.addEventListener("DOMContentLoaded", function(event) {
  var app = new Vue({
    el: '#app',
    data: {
      message: 'Hello Vue!'
    },
    created: function() {
      console.log('Vue instance was created');
    },
    methods: {
      exampleFunction: function() {
        console.log('This is an example function');
      }
    },
    destroyed: function() {
      console.log('Vue instance was destroyed');
    }
  })

  app.exampleFunction();
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
  <button v-on:click="exampleFunction">General</button>
</div>

关于javascript - v-on :click does not work (vue. js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48825182/

相关文章:

javascript - jquery img 未加载 "scr"

javascript - 动态填充表时突出显示和排序问题

html - 为什么形成丢失的 Bootstrap css?

vue.js - ValidationError : Invalid options object. Copy Plugin 已使用与 API 架构不匹配的选项对象进行初始化

vue.js - 视觉 : root element content and content distribution slots

javascript - Jquery ui 自动完成未显示,但显示在浏览器控制台上

javascript - jQuery 根据选择选项显示/隐藏 div

html - CSS 表格行背景色与表格背景色

php - HTML - 将来自 MySQL 数据库的 UTF-8 和特殊字符混合成 HTML

vue.js - 使用 axios 将文件发布到谷歌存储桶