简单的三步vuex入门

(编辑:jimmy 日期: 2024/9/27 浏览:2)

前言

之前几个项目中,都多多少少碰到一些组件之间需要通信的地方,而因为种种原因,
event bus 的成本反而比vuex还高, 所以技术选型上选用了 vuex, 但是不知道为什么,
团队里的一些新人一听到vuex,就开始退缩了, 因为vuex 很难"htmlcode">

// 引入vue 和 vuex
import Vue from 'vue'
import Vuex from 'vuex'

// 这里需要use一下,固定写法,记住即可
Vue.use(Vuex)

// 直接导出 一个 Store 的实例
export default new Vuex.Store({
 // 类似 vue 的 data
 state: {
 name: 'oldName'
 },
 // 类似 vue 里的 mothods(同步方法)
 mutations: {
 updateName (state) {
  state.name = 'newName'
 }
 }
})

代码看起来稍微有那么一点点多,不过看起来是不是很熟悉"htmlcode">

import Vue from 'vue'
import App from './App'
import vuexStore from './store' // 新增

new Vue({
 el: '#app',
 store:vuexStore     // 新增
 components: { App },
 template: '<App/>'
})

Tip: import store from './store' 后面的地址,就是上面我们新建那个文件的位置(/src/store/index.js),
因为我这里是index.js,所以可以省略.

第三步

以上2步,其实已经完成了vuex的基本配置,接下来就是使用了

文件位置 /src/main.js (同样是vue-cli生成的app.vue,这里为了方便演示,我去掉多余的代码)

<template>
 <div>
 {{getName}}
 <button @click="changeName" value="更名">更名</button>
 </div>
</template>

<script>
import HelloWorld from './components/HelloWorld'

export default {
 computed:{
 getName(){
  return this.$store.state.name
 }
 },
 methods:{
 changeName () {
  this.$store.commit('updateName')
 }
 }
}
</script>

这里就是一个很普通的vue文件了,有区别的地方是这里我们需要用computed属性去获取 store 里的 "data"

还有就是我们要改变数据的话,不再用 this.xxx = xxx 改成 this.$store.commit('updateName')

总结

你可能会觉得,上例这样做的意义何在,为何不直接用vue的data跟methods"_blank" href="https://www.jb51.net/article/140455.htm">VUEX进阶知识点巩固

分享给大家本文介绍的源码:https://github.com/noahlam/articles