国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

Vue三種常用傳值示例(父傳子、子傳父、非父子)

2024-05-06 15:32:33
字體:
來源:轉載
供稿:網友

1、父組件向子組件進行傳值:

父組件:

  <template>  <div>  父組件:  <input type="text" v-model="name">  <br>  <br>  <!-- 引入子組件 -->  <child :inputName="name"></child>  </div> </template> <script>  import child from './child'  export default {  components: {   child  },  data () {   return {   name: ''   }  }  } </script>

子組件:

 <template>  <div>  子組件:  <span>{{inputName}}</span>  </div> </template> <script>  export default {  // 接受父組件的值  props: {   inputName: String,   required: true  }  } </script>

2.子組件向父組件傳值

子組件:

  <template>   <div>   子組件:   <span>{{childValue}}</span>   <!-- 定義一個子組件傳值的方法 -->   <input type="button" value="點擊觸發" @click="childClick">   </div>  </template>  <script>   export default {   data () {    return {    childValue: '我是子組件的數據'    }   },   methods: {    childClick () {    // childByValue是在父組件on監聽的方法    // 第二個參數this.childValue是需要傳的值    this.$emit('childByValue', this.childValue)    }   }   }  </script> 

父組件:

 <template> <div> 父組件: <span>{{name}}</span> <br> <br> <!-- 引入子組件 定義一個on的方法監聽子組件的狀態--> <child v-on:childByValue="childByValue"></child> </div></template><script> import child from './child' export default { components: {  child }, data () {  return {  name: ''  } }, methods: {  childByValue: function (childValue) {  // childValue就是子組件傳過來的值  this.name = childValue  } } }</script>

3.非父子組件進行傳值。(非父子組件之間傳值,需要定義個公共的公共實例文件bus.js,作為中間倉庫來傳值,不然路由組件之間達不到傳值的效果。)

公共bus.js

//bus.jsimport Vue from 'vue'export default new Vue()

組件A:

<template> <div> A組件: <span>{{elementValue}}</span> <input type="button" value="點擊觸發" @click="elementByValue"> </div></template><script> // 引入公共的bug,來做為中間傳達的工具 import Bus from './bus.js' export default { data () {  return {  elementValue: 4  } }, methods: {  elementByValue: function () {  Bus.$emit('val', this.elementValue)  } } }</script>

組件B:

 <template>  <div>  B組件:  <input type="button" value="點擊觸發" @click="getData">  <span>{{name}}</span>  </div> </template> <script>  import Bus from './bus.js'  export default {  data () {   return {   name: 0   }  },  mounted: function () {   var vm = this   // 用$on事件來接收參數   Bus.$on('val', (data) => {   console.log(data)   vm.name = data   })  },  methods: {   getData: function () {   this.name++   }  }  } </script>            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 台前县| 聊城市| 大洼县| 澄江县| 银川市| 崇左市| 维西| 沙雅县| 诏安县| 山东省| 湘潭县| 巫溪县| 保康县| 安康市| 岳西县| 织金县| 房山区| 邵东县| 齐齐哈尔市| 凤山县| 徐汇区| 林甸县| 安西县| 汝南县| 赤水市| 九江市| 潮安县| 白朗县| 雅江县| 唐山市| 澄城县| 陕西省| 仁怀市| 盘锦市| 格尔木市| 高唐县| 汶川县| 南木林县| 高青县| 安丘市| 姜堰市|