我如何从组件更改 vuex 中的状态
我从 vuex 开始,有点困惑。我想在另一个组件(导航栏)中单击元素时显示购物车,并且购物车组件将显示在主视图中。这是我的代码: 导航栏
<img src="../assets/icons/cart-icon.svg" class="icon" @click="$store.commit('customChange')" />
家居
<div v-if="showCartHere">
<Cart />
</div>
<script>
import Cart from '../components/Cart.vue'
export default {
name: 'Home',
components: { Cart },
data() {
return {
showCartHere: false
}
},
mounted() {
this.showCartHere = this.$store.state.showCart
}
}
</script>
商店
import { createStore } from 'vuex'
export default createStore({
state: {
showCart: false
},
getters: {
showCart: state => {
return state.showCart
}
},
mutations: {
customChange(state) {
return state.showCart = !state.showCart
}
},
actions: {
customChange({ commit }) {
commit('customChange')
}
},
modules: {
}
})
I am starting with vuex and i am little bit confused. I want to show a cart when element is clicked in another component(navbar), and cart component will be shown inside home view. Here is my code:
Navbar
<img src="../assets/icons/cart-icon.svg" class="icon" @click="$store.commit('customChange')" />
Home
<div v-if="showCartHere">
<Cart />
</div>
<script>
import Cart from '../components/Cart.vue'
export default {
name: 'Home',
components: { Cart },
data() {
return {
showCartHere: false
}
},
mounted() {
this.showCartHere = this.$store.state.showCart
}
}
</script>
Store
import { createStore } from 'vuex'
export default createStore({
state: {
showCart: false
},
getters: {
showCart: state => {
return state.showCart
}
},
mutations: {
customChange(state) {
return state.showCart = !state.showCart
}
},
actions: {
customChange({ commit }) {
commit('customChange')
}
},
modules: {
}
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
组件
现在在您的 module/Cart.js 中
Component
Now in your module/Cart.js