<vuex第一弹>vuex之state和Mutation(前端网备份)
state为访问状态对象
Mutation为触发状态各人理解,这里做的是一些全局改变样式这种类似的操作
通过vue入口文件main.js里面开始
main.js
import store from './store/index'
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
写vuex的层
store/index.js
import Vue from 'vue' import Vuex from 'vuex' import state from './state' import mutations from './mutation' Vue.use(Vuex); export default new Vuex.Store({ state, mutations })
store/state.js
const state = { count : 44, bColor:"orange" } export default state;
store/mutation.js
const mutations = { jian(state){ state.count-- }, jia(state,n){ state.count+=n.a }, changeColor(state){ if(state.bColor == "orange"){ state.bColor = "blue" }else{ state.bColor = "orange" } } } export default mutations
调用vuex的组件层
<template> <div class="wrapper"> 我是list1_son {{$store.state.count}}-{{count}} <button @click="$store.commit('jia',num)">+</button> <!-- <button @click="jia(num)">+</button> --> <button @click="changeColor(bColor)">改变背景颜色</button> <div :style="{background:bColor}" class="text_bc">123</div> <button @click="jia(num)">+</button> <button @click="jian">-</button> </div> </template> <script> import { mapState, mapMutations } from "vuex"; export default { components: {}, props: {}, data() { return { num:{a:2}, }; }, watch: {}, //几种写法形式 // computed:{ // count(){ // return this.$store.state.count - 1 // } // }, // computed: mapState({ // count: state => state.count + this.num // }), //mapState简写在computed里;mapMutations简写在methods里 computed: { ...mapState({ count: state => state.count + 2, bColor: state => state.bColor }), }, methods: { //不简写的方法,直接在这里定义方法,在里面去传参 // jia(){ // let num = this.num; // this.$store.commit('jia',num) // }, //简写的方法必须在上面的@click="jia(num)"动态传参,目前只实现了这种形式 ...mapMutations({ jian: 'jian', jia:'jia', changeColor:'changeColor' }), }, created() { }, mounted() { console.log(this.$store.state.count); } }; </script> <style scoped> .wrapper { color: grey; } .text_bc{ background: orange; width:100px; height:100px; display: flex; align-items: center; text-align: center; justify-content: center } </style>