今天再看 github 上别人的项目时发现一个 vue 的小细节, 之前没有见过特写一篇文章记录一下......, 小细节为方法二.
方法一
子组件代码
- <template>
- <p @click="open"></p>
- </template>
- methods: {
- open() {
- this.$emit('showbox',true); // 触发 showbox 方法, true 为向父组件传递的数据
- }
- }
父组件
- <child @showbox="toshow" :msg="msg"></child> // 监听子组件触发的 showbox 事件, 然后调用 toshow 方法
- <p>{{ msg }}</p>
- data () {
- return {
- msg: false,
- }
- },
- methods: {
- toshow(msg) {
- this.msg = msg;
- }
- }
方法二
这个方法不用在父组件那里写自定义事件, 对于处理一些小数据简单易用, 推荐方法一 (毕竟更形象直观)
子组件代码
- <template>
- <p @click="open"></p>
- </template>
- methods: {
- open() {
- this.$emit('updata:mag',true); // 触发 showbox 方法, true 为向父组件传递的数据
- }
- }
父组件
- <child :msg="msg"></child> // 监听子组件触发的 showbox 事件, 然后调用 toshow 方法
- <p>{{ msg }}</p>
- data () {
- return {
- msg: false,
- }
- },
- methods: {
- toshow(msg) {
- this.msg = msg;
- }
- }
来源: https://www.2cto.com/kf/201805/743931.html