vue vuex
Vuex是做什么的?
Vuex是专门为Vue.js应用程序开发的状态管理模式
它采用 集中式存储管理 应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生改变
状态管理是什么?
你可以简单的将其看成把需要多个组件共享的变量全部存储在一个对象里面
然后把这个对象放在顶层的Vue实例中,让其他组件可以使用
Vuex提供了这样一个在多个组件间共享状态的插件,用它就可以了
使用vuex状态并且修改状态值:
<template>
<div class="home">
<!-- vuex共享状态 -->
<h1> vuex:{{$store.state.counter}}</h1>
<h1> vuex:{{$store.getters.poswerCounter}}</h1>
<!-- 通过 mutations 修改状态值 -->
<!-- commit的第一个参数是getters里面的方法名,第二个参数是传过去的参数(被称为是moutation的载荷payload) -->
<button @click="$store.commit('increment',false)">-</button>
<button @click="$store.commit('increment',true)">+</button>
</div>
</template>
vuex对象的定义:
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { counter: 0 }, mutations: { // 方法(修改state不能直接修改,要通过mutations 或 actions) increment(state,boo){ if(boo){ state.counter++ }else{ state.counter-- } } }, // 相当于vuex的计算属性 getters:{ poswerCounter(state){ return state.counter*state.counter } }, actions: { }, modules: { }, })
vuex的wantch这样写:
watch: { '$store.state.id':function(newFlag, oldFlag){ // 需要执行的代码 console.log(newFlag) this.catid = newFlag this.load_mall() } },

浙公网安备 33010602011771号