Imp*_*ura 3 javascript vue.js vue-router vue-component vuejs2
我使用Vue-Router将数据从一个组件传递到另一个组件时遇到问题。
我在主要组件中有此模板:
<li><router-link to="/">Daily</router-link></li>
<li><router-link to="/weekly/">Weekly</router-link></li>
<router-view></router-view>
Run Code Online (Sandbox Code Playgroud)
在我的DailyComponent
组件中,我具有以下数据功能:
data() {
return {
userCount: 0,
}
}
Run Code Online (Sandbox Code Playgroud)
第二个链接发送到名为的组件WeeklyComponent
。
如何将userCount: 0
数据从传递DailyComponent
到WeeklyComponent
,然后在那里显示?
谢谢!
这个问题更多的是关于如何构造组件以在它们之间共享数据的方式。有许多方法可以做到这一点,每种方法都有自己的优缺点,具体取决于情况。我建议您在stackoverflow / google中搜索执行此操作的方法,因为已经对此进行了深入讨论。
将userCount
数据所有者提升给父级
使父组件成为userCount
数据的所有者,然后通过prop将其传递给子组件。如果子组件要修改该数据,则它们必须$emit
具有父组件响应的具有新值的事件,以便它可以更新该值。
const Daily = {
props: ['userCount'],
template: '<p>Daily: {{ userCount }} <button @click="increment">+ 1</button></p>',
methods: {
increment() {
this.$emit('user-count', this.userCount + 1);
}
}
};
const Weekly = {
props: ['userCount'],
template: '<p>Weekly: {{ userCount }} <button @click="increment">+ 5</button></p>',
methods: {
increment() {
this.$emit('user-count', this.userCount + 5);
}
}
};
new Vue({
el: '#app',
router: new VueRouter({
routes: [
{ path: '/daily', component: Daily },
{ path: '/weekly', component: Weekly }
]
}),
data: {
userCount: 0,
},
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://rawgit.com/vuejs/vue/dev/dist/vue.js"></script>
<script src="https://rawgit.com/vuejs/vue-router/dev/dist/vue-router.js"></script>
<div id="app">
<router-link to="/daily">Daily</router-link>
<router-link to="/weekly">Weekly</router-link>
<router-view :user-count="userCount" @user-count="userCount = $event"></router-view>
</div>
Run Code Online (Sandbox Code Playgroud)
Vuex或其他一些外部状态管理
已经有很多Vuex示例,因此在这里我不会重复,但是您可以提出想要的任何状态管理系统。
在您的示例中,Vuex可能会过大。您可以只绕过共享的反应对象。
const Daily = {
props: ['shared'],
template: '<p>Daily: {{ shared.userCount }} <button @click="increment">+ 1</button></p>',
methods: {
increment() {
this.shared.userCount += 1;
}
}
};
const Weekly = {
props: ['shared'],
template: '<p>Weekly: {{ shared.userCount }} <button @click="increment">+ 5</button></p>',
methods: {
increment() {
this.shared.userCount += 5;
}
}
};
new Vue({
el: '#app',
router: new VueRouter({
routes: [
{ path: '/daily', component: Daily },
{ path: '/weekly', component: Weekly }
]
}),
data: {
shared: {
userCount: 0,
}
},
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://rawgit.com/vuejs/vue/dev/dist/vue.js"></script>
<script src="https://rawgit.com/vuejs/vue-router/dev/dist/vue-router.js"></script>
<div id="app">
<router-link to="/daily">Daily</router-link>
<router-link to="/weekly">Weekly</router-link>
<router-view :shared="shared"></router-view>
</div>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3545 次 |
最近记录: |