子传父

  vue子传父使用$emit传值

  子组件:

<template>
<div>
<button @click="toParent">点击传到父级</button>
</div>
</template>
<script>
export default {
name: 'child',
methods: {
toParent () {
this.$emit('fromChild', 'child')
}
}
}
</script>

父组件

<template>
<div>
<p>子级传过来的值:{{childVal}}</p>
<child @fromChild="getChild"></child>
</div>
</template>
<script>
import child from "@/components/child"; export default {
name: 'parent',
data () {
return {
childVal: ''
}
},
components: {
child
},
methods: {
getChild (v) {
this.childVal = v;
}
}
}
</script>

页面未点击前

vue子传父、父传子-LMLPHP

点击后

vue子传父、父传子-LMLPHP

传过来啦

父传子

  子组件使用props接收 接收时还可以设置默认值 当没获取到值时 会使用设置的默认值

父组件

<template>
<div>
<child :tochild="parentVal"></child>
</div>
</template>
<script>
import child from "@/components/child"; export default {
name: 'parent',
data () {
return {
parentVal: 'parent',
}
},
components: {
child
}
}
</script>

子组件

<template>
<div>
<p>父级传过来的值:{{tochild}}</p>
</div>
</template>
<script>
export default {
name: 'child',
props: {
tochild: String
}
}
</script>

效果

vue子传父、父传子-LMLPHP

父级定义的值 显示到子组件的里面啦 有没有很神奇 有没有想要试一试

05-02 09:56