vue傳值一般分三種方式:父組件向子組件傳值、子組件向父子間傳值、非父子組件進行傳值
一、父組件向子組件傳值:父組件引用子組件后,通過數據綁定(v-bind)向子組件傳值
父組件:
<template> <div> <h1>父組件</h1> <router-view v-bind:fatherData="data"></router-view> </div> </template> <script> export default { data () { return { data: '父組件數據data' }; } } </script>
子組件:把父組件傳遞過來的數據, 在 props數組 中定義一下,使用prop中接收的數據
<template> <div> <h1>子組件</h1> <p>父組件數據:{{fatherData}}</p> </div> </template> <script> export default { props: ['fatherData'], data () { return { }; } } </script>
二、子組件向父組件傳值:子組件通過事件向父組件傳值,通過$emit 觸發將子組件的數據當做參數傳遞給父組件
父組件:
<template> <div> <h1>父組件</h1> <router-view @show="showFather"></router-view> </div> </template> <script> export default { data () { return { sonData: '', sonData2: '' }; }, methods: { showFather (val1, val2) { this.sonData = val1;
this.sonData = val2;
console.log('子組件的值'+a+'=========='+b);
}
}
}
</script>
子組件:
<template> <div> <h1>子組件</h1> <Button type="primary" @click="sonClick">像父組件傳值</Button> </div> </template> <script> export default { data () { return { sonData1: '子組件第一個數據', sonData2: '子組件第二個數據' }; }, methods: { sonClick () { this.$emit('show', this.sonData1, this.sonData2); } } } </script>
三、非父子組件進行傳值:非父子組件之間傳值,需要定義個公共的公共實例文件bus.js,作為中間倉庫來傳值,不然路由組件之間達不到傳值的效果。
bus.js
//bus.js
import 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>