如何使用Vue.js将变量传递到同一级别的不同组件
我正在将Laravel 7与Vue.js 2一起使用 我的视图包含以下代码:如何使用Vue.js将变量传递到同一级别的不同组件,vue.js,Vue.js,我正在将Laravel 7与Vue.js 2一起使用 我的视图包含以下代码: @extends('layouts.app') @section('content') <div class="container"> <div id="app"> <report-meeting></report-meeting> <hr> <table-
@extends('layouts.app')
@section('content')
<div class="container">
<div id="app">
<report-meeting></report-meeting>
<hr>
<table-report></table-report>
</div>
</div>
@endsection
表报告:
<template>
<table class="table" v-bind:class="{invisible: success}">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john@example.com</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary@example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july@example.com</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
mounted() {
console.log('Component mounted.');
},
data: function() {
return {
success: true
}
},
methods: {
}
}
</script>
名字
姓氏
电子邮件
约翰
雌鹿
john@example.com
玛丽
教育部
mary@example.com
七月
杜利
july@example.com
导出默认值{
安装的(){
console.log(“组件安装”);
},
数据:函数(){
返回{
成功:真的
}
},
方法:{
}
}
我的想法是将变量success
从第一个组件传递到第二个组件。提交表单并通过验证步骤后,变量success
应变为false
,因此,即使表格的类不可见
,也应变为false
,表格将可见。
不幸的是,我不知道如何在两个组件之间连接变量success
。
是否有帮助?我建议,当两个兄弟组件需要“通信”时,父组件应该“促进”。报表组件可能会发出通知父级的事件,然后父级执行操作/设置属性以使表组件能够显示 在您的示例(laravel)中,
父组件
是可能在resources/js/app.js中定义的Vue实例(该Vue实例以“”为目标)。我不建议您将此全局实例用于此特定于页面的功能,因为您可能有更多页面。相反,您最好创建一个新组件作为父组件,并在页面/刀片中调用该组件
一些片段阐明了可能的解决方案:
@extends('layouts.app')
@section('content')
<div class="container">
<div id="app">
<reporter-app></reporter-app>
</div>
</div>
@endsection
我希望这能澄清一点。您的第三个代码片段对我来说不适用于get方法,但它只适用于post方法。。。也许你应该用“axios.get(url)”来更改你的axios调用?顺便问一下,如果变量“success”为真,那么表是可见的,是否可以这样做。。。然后,如果变量“success”变为false,表将返回隐形?有了你的代码片段,表格一出现就会一直可见。我根据你提供的代码片段,阐明了如何将这个成功信号引入到你的代码中。通过同样的方法,您可以添加另一个信号,可能是
this.$emit('failure')
,为了响应这个信号,您可以添加'@failure=“displayTable=false'''(在reporter app.vue中)。选择是无止境的;-)
@extends('layouts.app')
@section('content')
<div class="container">
<div id="app">
<reporter-app></reporter-app>
</div>
</div>
@endsection
// reporter-app.vue
<template>
<div>
<!-- listen for `success` events from report-meeting -->
<report-meeting @success="displayTable=true"></report-meeting>
<hr>
<!-- only displays when displayTable == true -->
<table-report v-if="displayTable"></table-report>
</div>
....
</template>
// report-meeting.
runReport: function() {
axios.get('api/get_report', this.formReport)
.then((response) => {
...
...
this.$emit('success')
})
}