日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > vue >内容正文

vue

vue --- 模块从子组件获取数据

發(fā)布時(shí)間:2023/12/10 vue 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。