我有一个如下所示的 Vue 应用程序:
index.html
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>vuejs-test01</title>
<link href="./src/assets/styles/style.css" type="text/css" rel="stylesheet" >
</head>
<body>
<div id="app">
<div id="bag"></div>
<div id="bag-helth">
<div :style="{ width:helth + '%' }"></div>
</div>
<div id="control">
<button @click="punch" v-show="!ended">click</button>
<button @click="restart">restart</button>
</div>
</div>
</body>
</html>
main.js
代码,在渲染函数中渲染 App.vue:
import Vue from 'vue'
import App from './App.vue'
import './assets/styles/global.styl'
new Vue({
el: '#app',
render: h => h(App),
})
我的style.css
代码,下面的css文件显示了样式:
#bag {
width: 200px;
height: 500px;
margin: 0 auto;
background: url(../imgs/02.png) center no-repeat;
background-size: 80%;
}
#bag-helth {
width: 200px;
border: 2px #000 solid;
margin: 0 auto 20px auto;
}
#bag-helth div {
height: 20px;
background: crimson;
}
#control {
width: 200px;
margin: 0 auto;
text-align: center;
}
我的Vue.app
代码,您会看到导出默认值
:
<template>
</template>
<script>
export default {
data: {
helth: 100,
ended: false,
},
methods: {
punch: function () {
this.helth -= 10
if (this.helth <= 0) {
this.ended = true
}
},
restart: function () {
this.helth = 100
this.ended = false
}
}
}
</script>
<style scoped>
</style>
在浏览器结果中:
当我点击按钮时,没有任何反应。
<小时/>EDIT-1
我发现如果在index.html
中,我在#bag
div中添加了值{{ helth }}
:
<div id="app">
<div id="bag">{{ helth }}</div>
...
模板不分析数据:
最佳答案
将您的 html 代码放在 App.vue
文件中 template
标记之间,而不是放在 index.html
中。所以你的 index.html
会像
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>vuejs-test01</title>
<link href="./src/assets/styles/style.css" type="text/css" rel="stylesheet" >
</head>
<body>
<div id="app"></div>
<script src="/dist/build.js"></script>
</body>
</html>
你的App.vue
就像
<template>
<div id="app">
<div id="bag">{{helth}}</div>
<div id="bag-helth">
<div :style="{ width:helth + '%' }"></div>
</div>
<div id="control">
<button @click="punch" v-show="!ended">click</button>
<button @click="restart">restart</button>
</div>
</div>
</template>
<script>
export default {
data: {
helth: 100,
ended: false,
},
methods: {
punch: function () {
this.helth -= 10
if (this.helth <= 0) {
this.ended = true
}
},
restart: function () {
this.helth = 100
this.ended = false
}
}
}
</script>
<style scoped>
</style>
关于javascript - 为什么绑定(bind)点击事件没有响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48731850/