vue组件传值
1.父传子
//父组件: <template> <div id="app"> <Children :msg="abc"/> </div> </template> <script> import Children from './components/children' export default { data() { return { abc:"123" } }, components:{ Children }, }
//子组件: <template> <div> <p>{{msg}}</p> </div> </template> <script> export default { props:{ msg:{ type:String } }, } </script>
子传父
//子组件: <template> <div> <button @click="sendHandle">点击</button> </div> </template> <script> export default { methods: { sendHandle(){ this.$emit("handle",123) } }, } </script>
父组件: <template> <div id="app"> <Children @handle="receiveHandle" /> </div> </template> <script> import Children from './components/children' export default { components:{ Children }, methods: { receiveHandle(val){ console.log(val); } }, } </script>
非父子传值
通过事件总线
//bus.js文件
import Vue from 'vue'
export default new Vue
//在需要传递消息的地方引入
import bus from './util/bus'
methods: {
sendMsg () {
bus.$emit('msg', '传参')
}
},
//在需要接受消息的地方使用bus.$on接受消息
mounted () {
bus.$on('msg', (val) => {
this.message= val
});

浙公网安备 33010602011771号