javascript - @click 事件在 vue.js 应用程序中不起作用
问题描述
我需要通过单击带有警报框的按钮来更改 {{message}}。没有显示警报框,消息也没有改变。
我是 vue 世界的新手,其他示例正在运行,但仅此文件存在问题。
我在标签内的消息标签上使用了指令“v-once” <h1>
,<h2>
没有“v-once”。
请回复我在下面的代码中做错了什么。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Vue.js Tutorial | Directives</title>
<script src="https://unpkg.com/vue@2.0.3/dist/vue.js"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div id="app">
<h1 v-once>{{message}}</h1>
<h2>{{message}}</h2>
<h5 v-show="viewed" v-html="intro"></h5>
</div>
<button @click="rewrite" type="button" name="button" >Change</button>
</body>
<script>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue World',
intro: 'Welcome to the Tutorial <small>It is all about Vue.js</small>',
viewed: true,
},
methods: {
rewrite: function () {
alert('Button Clicked!'),
this.message = 'Bye vue World!!!',
},
},
});
</script>
</html>
解决方案
您的代码的问题是您将按钮放在外部,div#app
因此 Vue 实例不会影响它。只需将按钮移动到里面div#app
就可以了
<body>
<div id="app">
<h1 v-once>{{message}}</h1>
<h2>{{message}}</h2>
<h5 v-show="viewed" v-html="intro"></h5>
// move button into here
<button @click.prevent="rewrite" type="button" name="button">Change</button>
</div>
</body>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Vue.js Tutorial | Directives</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div id="app">
<h1 v-once>{{message}}</h1>
<h2>{{message}}</h2>
<h5 v-show="viewed" v-html="intro"></h5>
<button @click.prevent="rewrite" type="button" name="button">Change</button>
</div>
</body>
<script>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue World',
intro: 'Welcome to the Tutorial <small>It is all about Vue.js</small>',
viewed: true,
},
methods: {
rewrite: function() {
alert('Button Clicked!')
this.message = 'Bye vue World!!!'
},
},
});
</script>
</html>
推荐阅读
- python - 如果字符串中有大括号,则 Python 正则表达式
- reactjs - JSS中是否有相当于背景颜色+图像的东西?
- javascript - 您的 xml 文件中有错误:not well-formed (invalid token) ?错误
- angular - 使用符号链接时,Windows 上的 Angular ng serve (angular-cli) 找不到资产文件
- angular - 角卡中的垂直截面
- fonts - 命令提示符中的字符 '!1' 和 '!2'
- c# - 谷歌对 /token 的期望是什么?
- javascript - HTML Canvas javascript 在 Z 轴上移动对象
- java - 与 TextWatcher 相关的代码仅适用于一个 EditView
- python - 从对列表中查找所有最大有向连接组