Last active
January 7, 2018 13:28
-
-
Save curder/dcf817db1cb1a35b90590686bb2e51c2 to your computer and use it in GitHub Desktop.
VueJs组件通讯-子组件给父组件传递事件演示,视频演示参考这里:https://www.bilibili.com/video/av10323610/index_24.html?t=312
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="zh-CN"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>VueJs组件通讯-自定义事件</title> | |
<link href="https://cdn.bootcss.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"> | |
</head> | |
<body> | |
<div id="app"> | |
<div class="container"> | |
<div class="col-md-3 ml-md-auto"> | |
<div class="card text-center"> | |
<div class="card-body"> | |
<h4 class="card-title" v-text="card.title"></h4> | |
<p class="card-text" | |
v-if="showText" | |
v-text="card.description"></p> | |
<toggle-btn v-on:toggle-card="toggleCard"></toggle-btn> | |
</div> | |
</div> | |
</div> | |
</div> | |
</div> | |
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.min.js"></script> | |
<script> | |
// 子组件 | |
Vue.component('toggle-btn', { | |
template: ` | |
<a href="#" | |
class="btn btn-primary" | |
v-on:click.prevent="emitToggle" | |
v-text="title"></a> | |
`, | |
data: function() { | |
return { | |
title: 'Toggle Description', | |
} | |
}, | |
methods: { | |
emitToggle(){ | |
this.$emit('toggle-card'); | |
} | |
} | |
}); | |
// 父组件 | |
var app = new Vue({ | |
el: '#app', | |
data: { | |
showText: true, | |
card:{ | |
title: 'Card title', | |
description: 'Some quick example text to build on the card title and make up the bulk of the card\'s content.', | |
} | |
}, | |
methods: { | |
toggleCard() { | |
this.showText = !this.showText; | |
} | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
click事件
,使用this.$emit()
传递给父组件的toggle-card
方法。v-on
绑定自定义事件,例如这里的toggle-card
。