vue03-vuex

是什么

组件间共享数据
登录状态、用户头像、地理位置
商品收藏、购物车中的物品

vuex一般创建文件夹store

安装vuex

cnpm install vuex@3.6.2 --save

创建store文件夹下面的index.js文件

import Vuex from 'vuex'
import Vue from 'vue'

//1.安装插件, 执行vuex.install方法
Vue.use(Vuex)  //Vuex not vuex

//2.创建vuex 对象(store)
const store = new Vuex.Store({
  state:{
    counter: 1000
  },
  mutations:{},
  actions:{},
  getters: {},
  modules: {}
})

//3.导出store对象
export default store

挂载到vue组件上,main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import store from "./store";

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store, //Vue.prototype.$store = store 注册
  render: h => h(App)
})

然后就可以使用了
<h2>{{$store.state.counter}}</h2>
image

$store是挂载在 Vue 实例上的(即Vue.prototype),而组件也其实是一个Vue实例,在组件中可使用 this 访问原型上的属性,template 拥有组件实例的上下文,
可直接通过{{ $store.state.userName }}访问,等价于 script 中的 this.$store.state.userName

image

vue component: --> 通过 actions --> mutation 修改state中的数据
devtools: 跟踪修改状态

mutations

image
image

然后这样调用

this.$store.commit('increment')
this.$store.commit('decrement')

vuex的store状态的更新唯一方式: 提交Mutation!!

Mutations 携带参数

这个参数叫 payload: 负载

如果参数过多playload可以传递一个 对象

//2.创建vuex 对象(store)
const store = new Vuex.Store({
  state:{
    counter: 1000
  },
  mutations:{
    inc(state) {
      state.counter++;
    },
    incByNum(state,count){
      state.counter += count;
    }
  },
  actions:{},
  getters: {},
  modules: {}
})

<template>
  <div>
    <h1>{{$store.state.counter}}</h1>
    <button @click="$store.commit('inc')">+</button>
    <button @click="incByNum(6)">+6</button>
    <button @click="$store.state.counter--">-</button>
  </div>
</template>

<script>
  export default {
    name: "Store1",
    methods: {
      incByNum: function(num){
        this.$store.commit('incByNum',num)
      }
    }
  }
</script>
posted @   超级氯化钾  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示