欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > vue >内容正文

vue

VueX的store的简单使用心结

发布时间:2023/12/13 vue 47 豆豆
生活随笔 收集整理的这篇文章主要介绍了 VueX的store的简单使用心结 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

vuex的特点:

多组件共享状态: 多个组件使用同一个数据
任何一个组件发生改变, 其他组件也要跟着发生相应的变化

安装vuex npm install vuex:

创建实例:

import Vuex from 'vuex' import Vue from 'vue' Vue.use(Vuex)const state = {name : '张三',age : 18 } const mutations = {// 更改 Vuex 的 store 中的状态的唯一方法是提交 mutationchangeName (state, params) {state.name = params.name},changeAge (state, params) {state.age = params.age} } const actions = {// Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutationactionsChangeAge ( context, params) {context.commit('changeAge', params)} } const getters = {// Getter 接受 state 作为其第一个参数doubleAge (state) {return state.age * 2}// 也可以使用箭头函数的简写// doubleAge: state => state.age * 2 }const store = new Vuex.Store({ // 创建全局状态管理的实例state, // 共同维护的全局状态mutations, // 处理数据的唯一途径, 修改state的数据只能通过mutationsactions, // 数据的异步操作处理getters // 获取数据并渲染 })// 导出并在main.js里面引用&注册 export default store# 引入文件: import Vue from 'vue' import App from './App.vue' import store from './store/index' Vue.config.productionTip = falsenew Vue({store, // 全局使用render: h => h(App), }).$mount('#app')# 模板:<template><div><h2>组件</h2><!-- 组件可以通过this.$store.state 获取store中的数据 -->name: {{ this.$store.state.name }} <br>age: {{ this.$store.state.age }}<button @click="change">修改年龄</button></div> </template> <script> export default {methods: {change () {// 此方法一般用于网络请求// dispatch: 调用actions里面的方法, 再让actions里面的方法// 通过commit 调用mutations里面的方法this.$store.dispatch('actionsChangeAge', { age: 120 })},changeName () {// 通过$store.commit直接调用store实例中mutation里面的方法// 参数1: 要调用mutation里面的方法名, 参数2: 要传输的数据this.$store.commit('changeName', { name: '宝宝', age: 19})}} } </script> ----------------------------------------------------------------// 以载荷形式 store.commit('increment'{amount: 10 //这是额外的参数 })// 或者使用对象风格的提交方式 store.commit({type: 'increment',amount: 10 //这是额外的参数 })dispatch:含有异步操作,数据提交至 actions ,可用于向后台提交数据 this.$store.dispatch('isLogin', true);commit:同步操作,数据提交至 mutations ,可用于读取用户信息写到缓存里 this.$store.commit('loginStatus', 1);state 存放基本数据 getters 从state基本数据派生出的数据(类似vue中的computed) mutations Store中更改state数据状态的唯一途径 actions 通过dispatch触发actions, actions在通过commit触发mutations。一般用于处理异步操作 modules 模块化Vuex

总结

以上是生活随笔为你收集整理的VueX的store的简单使用心结的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。