我有两个组件
我的第一个组件是这样的:
<template>
...
<ul class="dropdown-menu">
<li v-for="club in clubs"><a href="javascript:" @click="selectClub(club)">{{club.name}}</a></li>
</ul>
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<span @click="saveClub()">Ok</span>
</button>
</span>
...
</template>
<script>
import {mapActions} from 'vuex'
export default {
data() {
return {
clubs: [
{"id":1, "name":"chelsea", "coach":"conte", "stadium":"stamford bridge"},
{"id":2, "name":"manchester", "coach":"mourinho", "stadium":"old traford"},
{"id":3, "name":"liverpool", "coach":"klopp"," stadium":"anfield"}
],
clubSelected: {}
}
},
methods: {
selectClub(club) {
this.clubSelected = club
},
saveClub() {
this.setClub(this.clubSelected)
},
...mapActions(['setClub'])
}
}
</script>
我的第二个组件是这样的:
<template>
<div>
<button v-if="!getClub" type="button" class="btn btn-default">
<span class="fa fa-map-marker"></span> Select Club
</button>
<div v-else class="dropdown">
<button class="btn btn-default" type="button">
<span class="fa fa-map-marker"></span> {{getClub.name}}
</button>
</div>
</div>
</template>
<script>
import {mapGetters} from 'vuex'
export default {
computed: {
...mapGetters(['getClub'])
}
}
</script>
两个组件都通过模块 vuex 存储连接
我的模块 vuex 是这样的:
import { set } from 'vue'
...
const CART_KEY = 'clubApp'
// initial state
const state = {
status: null,
club: JSON.parse(localStorage.getItem(CART_KEY)),
}
// getters
const getters = {
getClub: state => state.club
getStatus: state => state.status
}
// actions
const actions = {
setClub ({ commit, state }, club)
{
// Check browser support
if (typeof(Storage) !== "undefined") {
//update club local storage
localStorage.setItem(CART_KEY, JSON.stringify(club))
commit(types.SET_CLUB_SUCCESS,{ club });
}
else
commit(types.SET_CLUB_FAILURE)
}
}
// mutations
const mutations = {
[types.SET_CLUB_SUCCESS] (state){
state.status = 'success'
},
[types.SET_CLUB_FAILURE] (state){
state.status = 'failure'
}
}
export default {
state,
getters,
actions,
mutations
}
如果我单击 Ok 按钮,它将调用 saveClub 方法。然后它将在模块 vuex 上调用 setClub 方法。然后它将数据存储在本地存储中
我希望当用户更改俱乐部时,它会自动更新。我的代码还不是自动的。当用户更换俱乐部时,不会自动更新
我怎么解决这个问题?
笔记 :
我想要这个代码:
<span class="fa fa-map-marker"></span> {{getClub.name}}
如果俱乐部发生变化,总是会改变