vue组件之间传值:
(1)父传子
原理: 父组件:利用自定义属性进行传值
子组件利用props进行接收使用
父组件
<template>
<div class="home">
<h1>父组件</h1>
//传递给儿子
<children :toson='toson'></children>
</div>
</template>
<script>
//引入子组件
import children from '@/views/Children'
export default {
name: 'home',
components: {
children
},
data(){
return {
toson:'给儿子的', //传递给儿子的数据
}
}
}
</script>
子组件
<template>
<div class="about">
<h1>子组件</h1>
<p>toson</p>
</div>
</template>
<script>
export default {
//接收父亲传递的数据
// props:['toson'],
props: {
toson: {
type: String
}
}
};
</script>
(2)子传父
原理:儿子:利用this.$emit('自定义事件',传输数据)
父亲:利用@自定义事件名=‘函数’ 进行接收
子组件
<template>
<div class="about">
<h1>子组件</h1>
//点击向父组件进行传值
<button @click="send">点击传递</button>
</div>
</template>
<script>
export default {
data() {
return {
aa: "儿子给父亲的",
};
},
methods: {
send() {
this.$emit("getson", this.aa);
}
}
};
</script>
父组件
<template>
<div class="home">
<h1>父亲</h1>
<children @getson='geta'></children>
</div>
</template>
<script>
import children from '@/views/Children'
export default {
name: 'home',
components: {
children,
},
data(){
return {
//定义接收的初始值
formson:''
}
},
methods:{
geta(data){
//接收来自儿子的数据
this.formson = data
}
},
}
</script>
(3)非父子关系之间传值 -(任意组件之间传值)
原理: 利用中间商bus,bus为vue的实例对象,向vue的实例对象的原型上添加vue实例
传值: this.bus.$emit('自定义事件',传值数值)
接收值:this.bus.$on('自定义事件',(data) => {})
1.main.js进行bus的创建
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
const bus = new Vue(); //创建vue实例
Vue.prototype.bus = bus; //向vue的原型链进行添加
new Vue({
router,
render: h => h(App)
}).$mount('#app')
2. 传递数据的组件
<template>
<div>
<h3>传递数据组件</h3>
<button @click='sendtoBrother'>向兄弟传值</button>
</div>
</template>
<script>
export default {
data(){
return {
toBrother:'给你的礼物'
}
},
methods:{
sendtoBrother(){
//进行传递值
this.bus.$emit('toborther',this.toBrother)
}
}
}
</script>
<style lang="scss" scoped>
</style>
3.接收的组件
<template>
<div class="about">
<h1>接收数据</h1>
</div>
</template>
<script>
export default {
data(){
return {
comeBrother:''
}
}
created(){
//进行接收数据
this.bus.$on('toborther',(data)=>{
//data兄弟传来的数据
this.comeBrother = data
})
}
};
</script>
(4)父组件修改子组件的值
父组件对子组件 - 引子注子用子,加一个标识 -ref
<exportAlert ref="exportAlert"></exportAlert>
修改: this.$refs.exportAlert.alertExport = true;