@ event является предпочтительным способом.
Я делал это в прошлом, передавая функцию в качестве опоры, но это антипаттерн, и его следует избегать. В любом случае, кроме этого предупреждения, вот как вы могли бы это сделать.
// 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)
}
},