美文网首页
vue脚手架使用vuex实现页面数据改变的小demo

vue脚手架使用vuex实现页面数据改变的小demo

作者: 执剑饮烈酒 | 来源:发表于2019-12-30 22:48 被阅读0次

第一步:下载vuex

cnpm install vuex -S

第二步:创建store文件夹,文件夹下创建index.js文件,配置文件

// 引入Vue

import vue from 'Vue'

// 引入Vuex

import vuex from 'Vuex'

// 使用vuex

vue.use(vuex)

// 创建仓库

let vuex = new vuex.Store({

    // 全局数据

    state : {

    },

    // 改变数据

    mutations:{

    }

})

第三步:main入口文件,引入index.js

import store from './store/index'

store挂载到vue实例

new Vue({

  el: '#app',

  router,

  components: { App },

  template: '<App/>',

  store

})

第四步:

App组件中访问定义的对象

console.log(this.$store.state.count) 

count定义的对象

访问得到的对象如图所示:

第五步:

App组件通过计算属性访问对象数据

computed: {

    count(){

      return this.$store.state.count

    }

  },

第六步:

页面使用定义的属性

页面效果如图所示:

数量:{{ this.$store.state.count }}

想修改数据就在store文件夹下的index.js文件中的

// 改变数据

    mutations:{

        add(state){

            state.count++

        }

    }

第七步:

然后在APP组件中定义方法add

<button @click="add">+</button>

第八步在APP组件中的methods中定义方法

methods: {

    add(){

      this.$store.commit('add')

    }

  },

想点击减号改变数据和点击加号一样的方法

在store文件夹下的index.js文件中的

// 改变数据

    mutations:{

        add(state){

            state.count--

        }

    }

然后在APP组件中定义方法jian

<button @click="jian">-</button>

第八步在APP组件中的methods中定义方法

methods: {

    jian(){

      this.$store.commit('jian')

    }

  },

页面效果如图所示:

这就是一个页面使用vuex的实现数据改变的效果

相关文章

网友评论

      本文标题:vue脚手架使用vuex实现页面数据改变的小demo

      本文链接:https://www.haomeiwen.com/subject/fajvoctx.html