父组件【tuwen - ftjbpage.vue】
Html 代码:调用子组件
<ftjbsendView :active="collectActive" :scriptid="scriptid" ref="sendView"></ftjbsendView>
父组件js
<script>
import ftjbsendView from './ftjbsendView';
import Cookies from 'js-cookie';
export default {
name: "ftjbpage",
data(){
return{
pid: this.$route.query.id,
scriptid: '',// 传递给子组件 案件详情id
collectActive: ''// 传递给子组件 标识收藏icon 是否已收藏 (1:收藏 0 未收藏)
}
},
created(){
//页面初始化 滚动到头部
document.documentElement.scrollTop=0;
document.body.scrollTop=0;
},
methods:{//请求接口 脚本详情
_getdetail(){
getscriptdetail(
{ parent_category_id: this.pid,.....},
{ token:Cookies.get('token'), platform: 'web' }
).then((res)=>{
if(res.content !==undefined){
this.detail = res;
this.scriptid = res.id;
if(res.collect === 0){
this.collectActive = false;
}else if(res.collect===1){
this.collectActive = true;
}
//通过refs.sendView 调用子组件方法changeActive =>为字段重新赋值
this.$refs.sendView.changeActive(this.collectActive);
}else{
alert('未找到案情脚本,请重新选择');
}
})
},
},
components:{
ftjbsendView, //声明子组件
}
}
</script>
子组件需要父组件传来2个参数,1个是active:bool,bool值,这个初始化的时候传来一次,后续在父组件中动态改变值后还需要再传一次,父组件中通过给组件声明名字
子组件html
<template>
<div class="footer" v-show="fav_send">
<div class="fav" @click="do_fav">
<i :class="{active:bool}"></i> ----1
<span>收藏</span>
</div>
</div>
</template>
子组件script
<script>
import axios from 'axios';
import Cookies from 'js-cookie';
export default {
name: "ftjbsendView",
props:['scriptid','active'], ---2 子组件通过props可以接收父组件传递来的数据,子组件就可以直接使用
data(){
return{
bool:'',
}
},
methods:{
changeActive(val){
this.bool = val;
},
_postIsLike(){
if(this.scriptid !== '') {
axios.post("http://xxx/api/script/collect?",
{
'id': this.scriptid, ----3 使用父组件传递来的数据
'uid': Cookies.get('id')
},
{
headers: {'token': Cookies.get('token'), 'platform': 'web'}
}
).then((is) => {
if (is.data.code === 200) {
alert(is.data.data.msg);
} else if (is.data.code === 401) {
alert('未登录')
} else if (is.data.code === 403) {
alert('未授权')
} else if (is.data.code === 422) {
alert('验证失败信息')
} else if (is.data.code === 500) {
alert('系统错误')
}
})
}else{
alert('请选择');
}
},
}
}
</script>
来源:oschina
链接:https://my.oschina.net/u/4415508/blog/3685908