一、父组件传值子组件
父组件传值子组件需要使用props 在子组件里定义一个props,即props:[‘msg’],msg可以是对象也可以是基本数据类型
如果你想定义一个默认值,即 props:{msg: {type: String, default: ‘hello world’}},
需要注意的是这种传值是单向的,你无法改变父组件的值(当然引用类型例外);而且如果直接修改props的值会报一个警告。
推荐的写法是在data()里重新定义一个变量(见Children.vue),并把props赋值给它,当然计算属性也行。
父组件代码
<template>
<!-- 在父组件内引入子组件,父组件通过属性将值传递给子组件-->
<Son :value-a="imgUrl" :value-b="alt"/>
</template>
<script>
import Son from '@components/son.vue'
export default {
name: 'father',
components: {
Son
}
}
</script>
子组件代码
<template>
<div class="img">
<img :src="valueA" :alt="valueB">
</div>
</template>
<script>
export default {
name: 'son',
// 子组件内部通过props接受传递过来的值
props: ['valueA','valueB']
}
</script>
二、子组件传值父组件
子组件传值父组件需要使用setup()
这里需要使用自定义事件,在子组件中使用this.$emit(‘myEvent’) 触发,然后在父组件中使用@myEvent监听
子组件代码
<script>
export default {
name: 'son',
data() {
return {
contentValue: this.value
}
},
watch: {
// contentValue随时监控data中的contentValue的值
contentValue (newValue) {
this.sayToFather(newValue)
},
},
setup(props, context) {
// 如果data中的contentValue有变化,watch会调用setup中的sayToFather,并赋值
const sayToFather = (e) => {
context.emit("listen", e)
}
return {
sayToFather,
}
}
}
</script>
父组件代码
<template>
<!-- 在父组件上导入子组件,引用,并添加@listen -->
<Son @listen="name"/>
</template>
<script>
// 引入子组件
import Son from '@components/son.vue'
export default {
name: 'father',
components: {
Son
},
setup() {
// ref的作用是实现响应式, 如果没有ref则不能实现响应式(引用数据类型用reactive)
let nameValue = ref('')
// 上面的listen="name"对应这里
let name = (val) => {
nameValue.value = val // 使用ref包裹的数据,需要通过.value的形式访问他的值
}
// 值需要return返回才可以使用
return {
nameValue,
name,
}
},
watch:{
// 在watch中监控值,若有变化,可赋值
nameValue(val){
console.log('nameValue: ' + val)
}
}
}
</script>
三、兄弟组件传值
1)定义一个公共的事件总线eventBus,通过它作为中间桥梁,我们就可以传值给任意组件了。而且通过eventBus的使用,可以加深emit的理解。
- EventBus.js
import Vue from 'vue'
export default new Vue()
- Children1.vue
<template>
<section>
<div @click="pushMsg">push message</div>
<br>
</section>
</template>
<script>
import eventBus from './EventBus'
export default {
name: "Children1",
components: {},
data() {
return {
childNum:0
}
},
methods: {
pushMsg(){
// 通过事件总线发送消息
eventBus.$emit('pushMsg',this.childNum++)
}
}
}
</script>
3.Children2.vue
<template>
<section>
children1传过来的消息:{{msg}}
</section>
</template>
<script>
import eventBus from './EventBus'
export default {
name: "Children2",
components: {},
data() {
return {
msg: ''
}
},
mounted() {
// 通过事件总线监听消息
eventBus.$on('pushMsg', (children1Msg) => {
this.msg = children1Msg
})
}
}
</script>
2)路由间传值
使用问号传值
#### A页面跳转B页面时使用
this.$router.push(’/B?name=danseek’)
#### B页面可以使用 [this.$route.query.nam](http://this.$route.query.name)e来获取A页面传过来的值
**上面要注意router和route的区别
使用冒号传值
配置如下路由:
{
path: '/b/:name',
name: 'b',
component: () => import( '../views/B.vue')
},
3)vuex传值
4)使用ref传值,通过ref的能力,给子组件定义一个ID,父组件通过这个ID可以直接访问子组件里面的方法和属性