我想将父组件中的道具传递给子组件。我的道具是tid
。
这是父组件:
<div id="tracksec" class="panel-collapse collapse">
<library :tid="track.category_id"></library>
</div>
这是子组件:
<script>
import Chapter from "./chapter";
import Http from "../../services/http/httpService";
export default {
components: {Chapter},
props:['tid'],
name: "library",
data(){
return{
library:{},
}
},
computed:{
getPr(){
return this.$props;
}
},
mounted(){
console.log(this.$props);
Http.get('/api/interactive/lib/' + this.tid)
.then(response => this.library = response.data)
.catch(error => console.log(error.response.data))
}
}
这是http源:
import axios from 'axios';
class httpService {
static get(url, params) {
if (!params) {
return axios.get(url);
}
return axios.get(url, {
params: params
});
}
static post(url, params) {
return axios.post(url, params);
}
}
export default httpService;
我想将tid
值传递给http.get
函数。例如:
Http.get('/api/interactive/lib/' + this.tid)
但tid
值为undefined
。
如何在挂载或创建的挂钩中获得tid
?
答案 0 :(得分:2)
我是Vue的新手,但我想你可能想要添加一个触发变化的“观察者”。您的“track-object”在创建时为空,这个前导track.category_id未定义。然后,当您从HTTP get获得答案时,您的值已设置,但未在库组件中更新。
这样的事情:
<script>
import Chapter from "./chapter";
import Http from "../../services/http/httpService";
export default {
components: {Chapter},
props:['tid'],
name: "library",
data(){
return{
library:{},
}
},
watch: {
// if tid is updated, this will trigger... I Think :-D
tid: function (value) {
console.log(value);
Http.get('/api/interactive/lib/' + value)
.then(response => this.library = response.data)
.catch(error => console.log(error.response.data))
}
},
computed:{
getPr(){
return this.$props;
}
},
mounted(){
console.log(this.$props);
// Will be undefined
/*
Http.get('/api/interactive/lib/' + this.tid)
.then(response => this.library = response.data)
.catch(error => console.log(error.response.data))*/
}
}
</script>
(不能测试代码,但你可能会得到这个想法)
答案 1 :(得分:1)
在父组件中尝试使用此代码片段
<div id="tracksec" class="panel-collapse collapse">
<library tid="track.category_id"></library>
</div>
然后在您的子组件代码中将如下所示:
<script>
import Chapter from "./chapter";
import Http from "../../services/http/httpService";
export default {
components: {
Chapter
},
props: [ 'tid' ],
name: 'library',
data () {
return {
library: {},
}
},
computed: {
getPr () {
return this.tid;
}
},
mounted () {
const tidValue = this.tid // get the value of props you've passed
console.log(tidValue) // check if it is getting the right value.
// code for http request.
}
}
</script>
答案 2 :(得分:0)
这是父脚本部分:
import Library from "./library";
import Http from '../../services/http/httpService';
export default {
components: {Library},
name: "interactive",
data() {
return {
track: {},
}
},
mounted() {
Http.get('/api/interactive/track/' + this.$route.params.id)
.then(response => this.track = response.data)
.catch(error => console.log(error.response.data))
}
}