Vue 之温习 component 的世界 - 3

props 是从 Vue 实体传送资料进去元件内,若是元件想要改变 Vue 实体本身的资料,这时候就会需要 emit 了
props 是一个方法,但 emit 是一个事件,即是一个需要被触发的事件,才会去更改外部的资料

首先建立一个元件跟一个点击 button 就会触发 addTotal 的事件:

<div id="app">  <h2>透过 emit 向外传递资讯</h2>  我透过元件储值了 {{ cash }} 元  <button class="btn btn-primary" @click="addTotal">按我</button>  <hr>  <button-counter></button-counter></div><script type="text/x-template" id="button-counter">  <div>    <button class="btn btn-outline-primary">增加 {{ counter }} 元</button>    <input type="number" class="form-control mt-2" v-model="counter">  </div></script><script>    Vue.component('buttonCounter', {      template: '#button-counter',      data: function() {        return {          counter: 10        }      }    });        var app = new Vue({      el: '#app',      data: {        cash: 300      },      methods: {        addTotal: function(){          this.cash = this.cash ++ ;        }      }    });</script>

接着要点击 button-counter 元件,来触发 Vue 实体的 addTotal 的事件,并改变 cash 的值:

首先 x-template 内会有自己的事件
<script type="text/x-template" id="button-counter">  <div>    <button @click="incrementCounter" class="btn btn-outline-primary">增加 {{ counter }} 元</button>    <input type="number" class="form-control mt-2" v-model="counter">  </div></script>
接着在 Vue.component() 内新增 methods 把 x-template 的事件写入进去,这就像是在 Vue 实体新增事件 function,只是现在是在元件内新增:
Vue.component('buttonCounter', {      template: '#button-counter',      data: function() {        return {          counter: 10        }      },      methods: {          incrementCounter: function(){                    }      }    });
接着在元件绑定一个自定义的事件,并指向外部我们要触发的事件 function:
<div id="app">  <h2>透过 emit 向外传递资讯</h2>  我透过元件储值了 {{ cash }} 元  <button class="btn btn-primary" @click="addTotal">按我</button>  <hr>  <!-- add 为自定义的名字 -->  <button-counter @add="addTotal"></button-counter></div>

到这就类似两边的桥梁都建好了,接下来只需要连接起来就可以了,所以
4. 在 Vue.component() 内的事件 function 使用 emit 方法,而我们要连结的值,就是在元件内自定义的事件:

Vue.component('buttonCounter', {      template: '#button-counter',      data: function() {        return {          counter: 10        }      },      methods: {          incrementCounter: function(){              this.$emit('add');          }      }    });

这时候我们点击 button-counter 就可以更改外部的 cash 的值了。


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章