1.父传子
<!-- 父组件 App.vue -->
<template>
<div id="app">
<Child :msg="msg"></Child>
</div>
</template>
<script>
import Child from './components/child.vue'
export default {
name: 'app',
data(){
return{
msg:'我是父组件的值',
}
},
components: {
Child
},
methods:{
}
}
</script>
<style>
</style>
--------------------------------------------------------------------------
<!-- 子组件 child.vue -->
<template>
<div>
<span>父组件传来的值:{{ msg }}</span>
</div>
</template>
<script>
export default {
name: 'Child',
props: {
msg: String
}
}
</script>
<style scoped>
</style>
结果:
这里有两种常见的试图变更一个 prop 的情形:
1.这个 prop 用来传递一个初始值;这个子组件接下来希望将其作为一个本地的 prop 数据来使用。在这种情况下,最好定义一个本地的 data property 并将这个 prop 用作其初始值:
props: {
msg: String
},
data() {
return {
message: this.msg
}
}
2.这个 prop 以一种原始的值传入且需要进行转换。在这种情况下,最好使用这个 prop 的值来定义一个计算属性:
props: {
num:Number
},
computed: {
isNum: function () {
return this.num*100
}
}
2.子传父
在上面基础上添加代码
<!-- 子组件 child.vue -->
<template>
<div>
<div>父组件传来的值:{{ msg }}</div>
<button type="button" @click="toFather()">传值给父组件</button>
</div>
</template>
<script>
export default {
name: 'Child',
props: {
msg: String
},
data() {
return {
message: this.msg,
childMessage:'childMessage'
}
},
methods: {
toFather(){
this.$emit('childFun',this.childMessage)
}
}
}
</script>
<style scoped>
</style>
----------------------------------------------------------------------------
<!-- 父组件 App.vue -->
<template>
<div id="app">
<Child :msg="msg" @childFun="getChild"></Child>
<div>子组件传来的值:{{childMsg}}</div>
</div>
</template>
<script>
import Child from './components/child.vue'
export default {
name: 'app',
data(){
return{
msg:'我是父组件的值',
childMsg:''
}
},
components: {
Child
},
methods:{
getChild(msg){
this.childMsg = msg
}
}
}
</script>
<style>
</style>
结果:
END