在子组件中的数据/状态在父元素使用
基本步骤描述:
1.在子组件中需要一个事件来触发如点击事件=>点击按钮执行xx
<button @click="onx">点我传递数据到上面</button>
2.在methods中定义好事件执行代码功能为利用$emit这个API触发子组件中的事件同时传递参数x:
methods:{
onx(){this.$emit("onx",this.x)}
}
3.在父组件中的插槽显示位置添加自定义事件名字与$emit第一个参数一样比如:<homess @onx="onxx"></homess>然后在methods中定义好事件onxx函数执行体中的代码示例代码如下:
//在子组件中:
<template>
<div>
<h3>我是子组件</h3>
<button @click="onadd">点我传递数据到父元素</button>
</div>
</template>
<script>
export default {
data() {
return {
x:'我是子组件内容我要去父组件'
}
},
methods:{
onadd(){
this.$emit("onx",this.x)
}
}
}
</script>
//在父组件中
<template>
<div>
<h1>我是父元素</h1>
<h1>{{content}}</h1>
<homess @onx="onxx"></homess>
</div>
</template>
<script>
import homess from "./homes.vue";
export default {
name: 'homes',
components: {
homess:homess,
},
data() {
return {
content:''
}
},
methods:{
onxx(content){
this.content=content
}
}
}
</script>
**父传子props**
// 在父组件中
<template >
<div>
<sun :mes="test"/>
</div>
</template>
<script>
import sun from './HomeSun.vue';
export default {
data() {
return {
test: {name: '盲僧',age: 36}
}
},
components:{
sun
},
</script>
**在子组件中**
<template lang="">
<div class="sun">
<h4>我是子组件&&&</h4>
{{mes.name}}--{{mes.age}}
</div>
</template>
<script>
export default {
// props:['mes'],第一种写法
props:{
mes: Object
} //第二种写法
}
</script>
```vue