可以在package.json文件里看到你的安装版本

2.1 先创建文件夹目录和js文件。

2.2 我的index.js代码(你们可以直接复制玩一下)
- import Vue from "vue"
- import Vuex from "vuex"
-
- Vue.use(Vuex);
-
- export default new Vuex.Store({
- state:{
- currDbSource: {},
- },
- mutations:{
- saveCurrDbSource(state,currDbSource){
- state.currDbSource = currDbSource;
- },
- }
- })
2.3 在main.js文件里引入全局 (注意一下引入的路径即可)
- // 引入vuex-store
- import store from './store/index';
-
- new Vue({
- el: '#app',
- router,
- store,
- render: h => h(App)
- });
这里我用click点击方法触发,用来存储数据 你们会玩了 可以灵活运用
- export default {
- data(){
- name:'小明'
- }
- methods:{
- click(){
- // 点击按钮进行一些操作,然后保存数据
- this.$store.commit('saveCurrDbSource',this.name)
- }
- }
- }
这里是我直接在我是打印出来的(哪个地方需要,可以直接去这样获取,然后再去赋值)
- mounted(){
- console.log('vuex数据',this.$store.state.currDbSource)
- }
运用computed来获取state的值(这样就可以拿到currDbSource整个对象了)
- computed:{
- currDbSource(){
- return this.$store.state.currDbSource
- }
- },
运用mapState来辅助获取state的值 (这样就可以拿到currDbSource整个对象了)
- import {mapState } from 'vuex'
-
- computed:{
- ...mapState(["currDbSource"])
- }
在页面上运用插值表达式进行渲染
{{testObj.name}}
自定义变量名字
- import {mapState } from 'vuex'
-
- computed:{
- ...mapState({
- names:(state)=>state.currDbSource
- })
- }
{{names.name}}
这个就是新手进门级别state的用法,还有进阶的用法。后续出