1.父组件向子组件传值–props
<template>
<div>
<hello-world :parentmsg="msg"></hello-world>
</div>
</template>
<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'home',
components: {
HelloWorld
},
data() {
return {
msg: '父组件传过来的值'
}
}
}
</script>
<template>
<div class="hello">
这是子组件--{{parentmsg}}
</div>
</template>
<script>
export default {
name: 'HelloWorld',
//props中的数据都是父组件传递给子组件的,只能读取,无法重新赋值
props: ['parentmsg'] //父组件传递过来的parentmsg属性,先在props定义一下
}
</script>
2.父组件向子组件传递方法—$emit
<template>
<div>
<!-- 父组件向子组件传递方法使用的是事件绑定机制 -->
<hello-world :parentmsg="msg" @func="show"></hello-world>
</div>
</template>
<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'home',
components: {
HelloWorld
},
methods: {
show() {
console.log('调用了父组件的方法')
}
},
}
</script>
<template>
<div class="hello">
<input type="button" value="这是父组件传递过来的方法" @click="myClick ">
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: ['parentmsg'],
methods: {
myClick() {
this.$emit('func')
}
}
}
</script>
3.子组件向父组件传值 – 通过方法拿到子组件的值
<template>
<div>
<!-- 父组件向子组件传递方法使用的是事件绑定机制 -->
<hello-world @func="show"></hello-world>
</div>
</template>
<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'home',
components: {
HelloWorld
},
data() {
return {
sonmsg: null
}
},
methods: {
show(data) {
this.sonmsg = data
console.log('调用了父组件的方法')
}
},
}
</script>
<template>
<div class="hello">
<input type="button" value="这是父组件传递过来的方法" @click="myClick ">
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: ['parentmsg'],
data() {
return {
params: {
name: "cc",
age: 18
}
}
},
methods: {
myClick() {
this.$emit('func', params)
}
}
}
</script>