我对VueJ比较陌生,我被困在一个项目上,我无法在网上找到解决方案。
我希望有一个变量逗号到所有页面(月份),当这个变量发生变化时,我希望能够在我的页面上做一些事情。
我想做什么的例子(简化)
在App.vue中
<div id="app">
<div id="topBar">
<div id="nav">
<div><router-link to="/">Home</router-link></div>
<div><router-link to="/expenses">Dépenses</router-link></div>
<div><router-link to="/revenues">Revenus</router-link></div>
<div><router-link to="/category">Categories</router-link></div>
</div>
</div>
<select name="selectMonth" v-model="month" id="selectMonth" required>
<option v-for="(month, index) in months" :key="index" :value=month>{{ month }}</option>
</select>
<router-view/>
</div>在Home.vue或任何其他页面中
watch: {
month: function () {
this.getExpenses() // or something else (In this case I want to fetch data again with a new month)
}
},但是由于变量在app.vue上被更改了(不管我在哪个页面上),所以我不能在页面上看到它。
你知道我该怎么做吗?这类事情的最佳实践是什么?
如果有人能帮我的话,提前谢谢!
编辑:已解决的
国家管理和$emit做到了这一点。当我发现Vuex时,我发现我的应用程序不需要这么大的国家经理,所以我找到了另一种方法(基于同样的想法):
我用一个空的Vue实例创建了一个bus.js:
import Vue from 'vue'
const bus = new Vue()
export default bus然后在我的组件中使用
import bus from '../bus'
...
onChangeMonth () {
bus.$emit('new-month', this.month)
},在我的页面上:
import bus from '../bus'
...
created () {
bus.$on('new-month', this.getExpenses)
},发布于 2020-01-03 16:52:29
基于组件的UI框架(如Vue、React和friends )实施了将数据向下传递到组件(Vue中的道具)的想法,但不允许这些组件通过简单地更改数据将更新传递给父级。造成这种情况的原因是性能;进行数据更改显式地允许框架只在需要时重新呈现。
与更新传递到组件中的道具不同,更新可以通过事件传递给向上,或者使用像维克斯这样的状态管理器。
如果您正在寻找实现这一目标的简单方法,请查看$.emit:https://v2.vuejs.org/v2/api/#vm-emit
https://stackoverflow.com/questions/59582197
复制相似问题