vue VUEX的安装与使用

博客介绍了Vuex的使用方法,包括安装命令npm i vuex -s,引入和配置,state数据的调用与修改,可通过mutations同步修改,也能用this.$set或this.$delete操作。还提及getters处理属性值,Actions异步调用mutations,以及扩展运算符的调用方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vuex的安装 npm i vuex -s
npm i vuex -s
引入和配置
在src目录下新建 store文件夹 在store文件夹下新建 index.js 即:src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

// 挂载Vuex
Vue.use(Vuex)

// 创建VueX对象
const store = new Vuex.Store({
  state: {
    // 存放的键值对就是索要管理的状态
    name: '赵丽颖'
  }
})

export default store

在main.js中引入该文件
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import * as filters from './filters'
import store from './store' // 点1

Vue.config.productionTip = false

Object.keys(filters).forEach(key => { Vue.filter(key, filters[key]) })

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,  // 点2
  components: { App },
  template: '<App/>'
})

state数据中的调用
模板调用
<template>
<div>
  <div>
    明星姓名: {{$store.state.name}}
  </div>
</div>
</template>
js中调用
    console.log(this.$store.state.name) // 赵丽颖
state值得修改 通过mutations进行调用 使用this.$store.commit(方法名,值) 同步时使用
注:不要直接进行修改state得值,需要通过mutations或者Vue.set() 或者 this.$set() 进行修改

同步时调用,异步使用Actions
import Vue from 'vue'
import Vuex from 'vuex'

// 挂载Vuex
Vue.use(Vuex)

// 创建VueX对象
const store = new Vuex.Store({
  state: {
    // 存放的键值对就是索要管理的状态
    name: '赵丽颖'
  },
  mutations: { // 通过调用这里得方法,进行修改state中的值
    nameEdit (state, val = '') {
      state.name = val
    }
  }
})

export default store

调用
    this.$store.commit('nameEdit', '赵文卓')
    console.log(this.$store.state.name) // 赵文卓
this.$set设置/更改 或者 this.$delete删除 state内的值
    this.$set(this.$store.state, 'age', 32) // 设置新值
    console.log(this.$store.state.age) // 32

    this.$set(this.$store.state, 'age', 23) // 更改
    console.log(this.$store.state.age) // 23

    this.$delete(this.$store.state, 'age') // 删除
    console.log(this.$store.state.age) // undefined
getters 用于将属性值处理后返回
语法:
getters: {
	func1(state) {
		return state.属性值 + 其它的信息等
	},
	func2(state,getters) {
		return getters.func1 + state.属性值 + 其它额信息等
	}
}

参数
第一个参数即state
第二个参数即getters本身,也就是说getters下的方法可以随时调用其它的getters方法

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

// 挂载Vuex
Vue.use(Vuex)

// 创建VueX对象
const store = new Vuex.Store({
  state: {
    // 存放的键值对就是索要管理的状态
    name: '赵丽颖',
    school: '中南大学'
  },
  mutations: {
    nameEdit (state, val = '') {
      state.name = val
    }
  },
  getters: {
    nameInfo (state) {
      return `${state.name}是个大明星`
    },
    // 可以传参getters,调用自身
    fromInfo (state, getters) {
      return `${getters.nameInfo},并且毕业于${state.school}`
    }
  }
})

export default store

    console.log(this.$store.getters.nameInfo) // 赵丽颖是个大明星
    console.log(this.$store.getters.fromInfo) // 赵丽颖是个大明星,并且毕业于中南大学
Actions 的异步调用mutations修改state内的值
actions:{
	func1(content,其它参数){ // 其中content是整个store的大对象,其中包括state\getters\mutations等
		return new Promise(resolve => {
			content.commit(mutations中的参数,其他参数)
			resolve()
		})
	}
}
import Vue from 'vue'
import Vuex from 'vuex'

// 挂载Vuex
Vue.use(Vuex)

// 创建VueX对象
const store = new Vuex.Store({
  state: {
    // 存放的键值对就是索要管理的状态
    name: '赵丽颖',
    school: '中南大学'
  },
  mutations: {
    nameEdit (state, val = '无名氏') {
      state.name = val
    }
  },
  getters: {
    nameInfo (state) {
      return `${state.name}是个大明星`
    },
    // 可以传参getters,调用自身
    fromInfo (state, getters) {
      return `${getters.nameInfo},并且毕业于${state.school}`
    }
  },
  actions: {
    setName (content, val = '无名氏') { // 第一个参数:content就是一份$store这个对象;;第二个参数则是调用时候后面的参数
      console.log(content) // 包含了state\getters\mutations等等
      return new Promise(resolve => {
        content.commit('nameEdit', val)
        resolve()
      })
    }
  }
})

export default store

调用 this.$store.dispacth('setName',其他参数)
    console.log(this.$store.state.name) // 赵丽颖
    await this.$store.dispatch('setName', '王富贵') // 因为使用了await,所以最外层需要使用async
    console.log(this.$store.state.name) // 王富贵
如果Actions方法中只需要使用到mutations中的方法,则可以直接在接参的时候解构处{commit},在方法中直接使用commit()
import Vue from 'vue'
import Vuex from 'vuex'

// 挂载Vuex
Vue.use(Vuex)

// 创建VueX对象
const store = new Vuex.Store({
  state: {
    // 存放的键值对就是索要管理的状态
    name: '赵丽颖',
    school: '中南大学'
  },
  mutations: {
    nameEdit (state, val = '无名氏') {
      state.name = val
    },
    schoolEdit (state, val = '未知大学') {
      state.school = val
    }
  },
  getters: {
    nameInfo (state) {
      return `${state.name}是个大明星`
    },
    // 可以传参getters,调用自身
    fromInfo (state, getters) {
      return `${getters.nameInfo},并且毕业于${state.school}`
    }
  },
  actions: {
    setName (content, val = '无名氏') { // 第一个参数:content就是一份$store这个对象;;第二个参数则是调用时候后面的参数
      console.log(content) // 包含了state\getters\mutations等等
      return new Promise(resolve => {
        content.commit('nameEdit', val)
        resolve()
      })
    },
    setSchool ({commit}, val = '未知大学') { // 第一个参数为解构后的
      return new Promise(resolve => {
        commit('schoolEdit', val) // 直接使用commit即可
        resolve()
      })
    }
  }
})

export default store

    console.log(this.$store.state.school)
    await this.$store.dispatch('setSchool', '北京大学')
    console.log(this.$store.state.school)
扩展运算符对state等的调用方式 …mapState() …mapGetters() …mapMutations() …mapActions()
语法:
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'

...mapState({别名:'原名',别名:'原名'})
this.别名

...mapGetters(别名:'原名',别名:'原名')
this.别名

...mapMutations(别名:'原名',别名:'原名')
this.别名(替换的值)

...mapActions(别名:'原名',别名:'原名')
await this.别名(替换的值)
<!--  -->
<template>
<div>
</div>
</template>

<script>
import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'
export default {
  name: 'VueBase',
  data () {
    return {

    }
  },
  computed: {
    ...mapState({
      storeName: 'name',
      storeSchool: 'school'
    }),
    ...mapGetters({
      storeNameInfo: 'nameInfo'
    })
  },
  filters: {
  },
  methods: {
    ...mapMutations({
      storeNameEdit: 'nameEdit'
    }),
    ...mapActions({
      actionSetSchool: 'setSchool'
    })
  },
  // 生命周期 - 创建完成(访问当前this实例)
  async created () {
    // state属性
    console.log(this.storeName)
    console.log(this.storeSchool)
    console.log(this.address)

    // getter
    console.log(this.storeNameInfo)

    // munitation
    this.storeNameEdit('张朝阳')
    console.log(this.storeName) // 张朝阳

    // action的使用
    await this.actionSetSchool('清华大学')
    console.log(this.storeSchool) // 清华大学
  },
  // 生命周期 - 挂载完成(访问DOM元素)
  mounted () {
  }
}
</script>
<style scoped>
/* @import url(); 引入css类 */

</style>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值