<h3><strong>父组件代码:</strong></h3>
<template>
<div class="my_index">
<!-- 文章详情 -->
<artical-detail
v-if="isShow"
@getShow="getShow"
:detail_title='detail_title'
:detail_pic="detail_pic"
:detail_content="detail_content"
></artical-detail>
</div>
</template>
<script>
import articalDetail from "../articalDetail/articalDetail";
import axios from 'axios'
export default{
name:'myIndex',
data(){
return{
articalList:[], // 文章详情
isShow:false, // 文章是否显示
detail_title:'',
detail_pic: '',
detail_content: ''
}
},
components:{
articalDetail
},
methods:{
// 获取文章信息
getArticalInfo:function(res){
res = res.data
res.data.forEach((item,index,arr) => {
this.articalList.push(item)
// console.log(this.articalList)
})
},
// 跳转到详情页
toDetail:function (res) {
this.isShow = true; // 改变为文章详情显示
// console.log(res.artical_title)
this.detail_title = res.artical_title // 设置title
this.detail_pic = res.artical_pic // 设置图片
this.detail_content = res.artical_content // 设置内容
},
// 子组件点击返回让文章详情隐藏
getShow:function (data) {
this.isShow = data
}
},
mounted() {
// axios请求文章列表
axios({
url:'***',
methods:'get',
}).then(this.getArticalInfo)
}
}
</script>
子组件代码:
<template>
<div class="detail">
<div class="toBack">
<p @click="toBack">返回</p>
</div>
<h1 class="detail_title">{{detail_title}}</h1>
<img class="detail_pic" :src="detail_pic">
<div class="detail_content">
<p>{{detail_content}}</p>
</div>
</div>
</template>
<script>
export default {
name: "articalDetail",
data(){
return{
isShow:false
}
},
// 父组件传值给子组件,子组件通过props属性接收
props:{
detail_title:String,
detail_pic:String,
detail_content:String
},
methods:{
// 子组件通过$emit传值给父组件
toBack:function(){
this.$emit("getShow",this.isShow)
}
}
}
</script>
总结:
父组件给子组件传值:
父组件data中声明子组件需要的字段
父组件通过一个方法去到子组件,通过给该方法传参
改变父组件data中的声明的子组件需要的字段为传给子组件的值
在父组件中的子组件标签上绑定子组件需要的key值等于父组件data中传给子组件的key值
子组件中通过props属性接收,设置子组件需要的key值的数据类型
在子组件中通过使用文本插值的方法将props属性中接收到的值渲染到页面
子组件给父组件传值:
子组件通过一个方法去到父组件
该方法中使用this.$emit方法,第一个参数为父组件的自定义事件,第二个参数为传过去的值
父组件给自定义事件添加一个方法,该方法中有一个参数,该参数为子组件传过来的值
说的可能不是很清楚,该篇博客是http://xueshuai.top中文章列表与文章详情之间的传值