一、字符串反转:实现点击按钮后,字符串反过来显示
- 写按钮,并绑定事件方法:v-on(绑定一个事件):click(绑定的是click事件)
<button v-on::click="handleBtnClick">反转</button>
- 定义点击事件函数:
methods: {
handleBtnClick() {
this.content = this.content.split('').reverse().join('')
}
},
完整代码如下:
<!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.0">
<title>2</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
<script>
Vue.createApp({
data() {
return {
content: 'hello world'
}
},
methods: {
handleBtnClick() {
this.content = this.content.split('').reverse().join('')
}
},
template: `
<div>
{{content}}
<button v-on:click="handleBtnClick">反转</button>
</div>
`
}).mount('#root')
</script>
</body>
</html>
二、点击按钮后可展示或隐藏页面内容
- 增加一个数据变量:show
data() {
return {
show: true
}
},
- 给内容绑定v-if属性,用于控制显隐
<span v-if="show">hello world</span>
- 改点击事件内容
methods: {
handleBtnClick() {
this.show = !this.show;
}
},
完整代码如下:
<!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.0">
<title>2</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
<script>
Vue.createApp({
data() {
return {
show: true
}
},
methods: {
handleBtnClick() {
this.show = !this.show;
}
},
template: `
<div>
<span v-if="show">hello world</span>
<button v-on:click="handleBtnClick">显示/隐藏</button>
</div>
`
}).mount('#root')
</script>
</body>
</html>