vue父子传值和非父子传值
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>

浙公网安备 33010602011771号