@event是首选方式。
我过去通过将函数作为 prop 传递来完成此操作,但这是一种反模式,应该避免。不管怎样,除了警告之外,你可以这样做。
// child.vue
<template>
<div>
{{getData}}
</div>
</template>
<script>
export default {
name: 'Contributors', // this is the name of the component
data () {
return {
getData: null
}
},
props: {
setAppGetData: {
type: Function,
},
},
mounted () {
this.$http
.get('https://api.github.com/repos/moumen-soliman/frontend-helper/stats/contributors')
.then(response => (this.getData = response.data.reverse()))
.then(() => (this.setAppGetData(this.getData) ) // run function here
.catch(error => console.log(error.response))
},
}
</script>
// app.vue
<template>
<div id="app">
<contributors :setAppGetData="setAppGetData"/> //here just pass json data but I can't control it or make it equal variable in app.vue
{{appGetData}} // i need to make it data equal current variable in parent data
</div>
</template>
<script>
export default {
name: 'App',
data () {
return {
appGetData: null // I need something like this
}
},
methods: {
setAppGetData (data) {
this.appGetData = data
}
}
}
</script>
但在我看来,在这种情况下,倾听者可能仍然工作得更好并且更容易。您可以添加另一个then
或使用内部watch
触发该事件
那么再一个
mounted () {
this.$http
.get('https://api.github.com/repos/moumen-soliman/frontend-helper/stats/contributors')
.then(response => (this.getData = response.data.reverse()))
.then(() => (this.$emit('dataLoaded', this.getData) ) // emit data
.catch(error => console.log(error.response))
},
使用手表
watch: {
getData(newValue) {
this.$emmit('dataUpdated', newValue)
}
},