vue --- 模块从子组件获取数据
生活随笔
收集整理的這篇文章主要介紹了
vue --- 模块从子组件获取数据
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
先看個(gè)一般的例子:
// 我們需要將信息從子組件傳遞給父組件,(有可能不止一條信息,因此)肯定需要一個(gè)標(biāo)識(shí),這個(gè)標(biāo)識(shí)放在$emit里面(js),在dom中通過@來關(guān)聯(lián)父元素。如下:<div id = "app"><transfer @connect="sayConnect" @build="sayBuild"></transfer> </div>// js <script>Vue.component('transfer',{template:'<button @click="send1">發(fā)送connect</button><br>'+'<button @click="send2">發(fā)送build</button>',methods:{send1(){this.$emit('connect');},send2(){this.$emit('build');}}});// 子組件注冊了2個(gè)方法,send1和send2,點(diǎn)擊send1發(fā)送connect,點(diǎn)擊send2發(fā)送build.// @connect="sayConnect", connect對應(yīng)子組件中this.$emit('connect').sayConnect對應(yīng)父組件的sayConnect方法,下面寫出來.// 注意,在子模版中,按鈕的綁定使用的是@而不是:let vm = new Vue({el:"#app",methods:{sayConnect(){console.log('connect success!');},sayBuild(){console.log('build success');}}}); </script>接下來,看個(gè)更復(fù)雜一點(diǎn)的例子:
假設(shè)我們希望:
點(diǎn)擊"+1",總數(shù)加1;點(diǎn)擊"-1"總數(shù)減1. 且數(shù)據(jù)是來自子組件…
首先寫html
<div id = "app"><p>總數(shù) {{ total }} </p><my-component @increase="handleTotal" @reduce="handleTotal"> </div> </div> // 說明: total 是父元素的 // @increase 對應(yīng) 子組件中的 $emit('increase', data); // @reduce 對應(yīng) 子組件中的 @emit('reduce', data); // handleTotal對應(yīng)父組件中methods方法中的 handleTotal方法掛載Vue,注冊組件
<script>// 組件應(yīng)該在vue掛載之前注冊Vue.component('my-component',{ // 第一個(gè)參數(shù)組件名,對應(yīng)html中的<my-component></my-component>// 首先寫替換<my-component>的templatetemplate:'\<div>\<button @click = "handleIncrease"> +1 </button>\<button @click = "handleReduce">-1 </button>\<div>',// ps: template中 寫了2個(gè)點(diǎn)擊事件 handleIncrease 和 handleReduce , 由于要傳一個(gè)數(shù)據(jù)給父元素,我們定義如下:data: function (){return {counter: 0;}}, // 子元素中的counter 初始化為0methods: {handleIncrease: function() {this.counter++;this.$emit('increase', this.counter);},handlerReduce: function() {this.counter--;this.$emit('reduce', this.counter);}}}); // 子模塊完畢// 說明: $emit(a,data)用來像父元素傳遞信息, 父元素用@'a'的形式接受信息// 開始掛載vue(在此是父元素).var app = new Vue({el: '#app',data: {total: 0 // 對應(yīng)html <p>{{total}} </p>},methods:{handleTotal: function (total ){ // total 參數(shù)來自于 $emit的第二個(gè)參數(shù)..this.total = total; }}})</script>總結(jié)
以上是生活随笔為你收集整理的vue --- 模块从子组件获取数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springBoot+Vue导出Exce
- 下一篇: 计算机网络技术教材多少钱,计算机网络技术