iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >使用Vuex的案例分析
  • 184
分享到

使用Vuex的案例分析

2024-04-02 19:04:59 184人浏览 八月长安
摘要

这篇文章给大家分享的是有关使用Vuex的案例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。什么是Vuex?vuex是专门为vue.js应用程序开发的一种状态管理模式,当多个视

这篇文章给大家分享的是有关使用Vuex的案例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

什么是Vuex?

vuex是专门为vue.js应用程序开发的一种状态管理模式,当多个视图依赖于同一个状态或是多个视图均可更改某个状态时,将共享状态提取出来,全局管理。

引入Vuex(前提是已经用Vue脚手架工具构建好项目)

1、利用npm包管理工具,进行安装 vuex。在控制命令行中输入下边的命令就可以了。

npm install vuex --save

要注意的是这里一定要加上 –save,因为你这个包我们在生产环境中是要使用的。

2、新建一个store文件夹(这个不是必须的),并在文件夹下新建store.js文件,文件中引入我们的vue和vuex。

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

3、使用我们vuex,引入之后用Vue.use进行引用。

Vue.use(Vuex);

通过这三步的操作,vuex就算引用成功了,接下来我们就可以尽情的玩耍了。

4、在main.js 中引入新建的vuex文件

import storeConfig from './vuex/store'

5、再然后 , 在实例化 Vue对象时加入 store 对象 :

 new Vue({
  el: '#app',
  router,
  store,//使用store
  template: '<App/>',
  components: { App }
 })

下面是一个计数器的例子

在src目录下创建一个store文件夹。

src/store.js

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

Vue.use(Vuex)

const store = new Vuex.Store({
 state: {
 count: 0,
 show: ''
 },
 getters: {
 counts: (state) => {
  return state.count
 }
 },
 mutations: {
 increment: (state) => {
  state.count++
 },
 decrement: (state) => {
  state.count--
 },
 changTxt: (state, v) => {
  state.show = v
 }
 }
})

export default store

state就是我们的需要的状态,状态的改变只能通过提交mutations,例如:

handleIncrement () {
  this.$store.commit('increment')
 }

带有载荷的提交方式:

chanGobj () {
  this.$store.commit('changTxt', this.obj)
 }

当然了,载荷也可以是一个对象,这样可以提交多个参数。

changObj () {
  this.$store.commit('changTxt', {
   key:''
  })
 }

在main.js中引入store.js

import store from './store/store'
export default new Vue({
 el: '#app',
 router,
 store,
 components: {
 App
 },
 template: '<App/>'
})

在组件中使用

在组建可以通过$store.state.count获得状态

更改状态只能以提交mutation的方式。

<template>
<div class="store">
 <p>
 {{$store.state.count}}
 </p>
 <el-button @click="handleIncrement"><strong>+</strong></el-button>
 <el-button @click="handleDecrement"><strong>-</strong></el-button>
 <hr>
 <h4>{{$store.state.show}}</h4>
 <el-input
 placeholder="请输入内容"
 v-model="obj"
 @change="changObj"
 clearable>
 </el-input>
</div>
</template>
<script>
export default {
 data () {
 return {
  obj: ''
 }
 },
 methods: {
 handleIncrement () {
  this.$store.commit('increment')
 },
 handleDecrement () {
  this.$store.commit('decrement')
 },
 changObj () {
  this.$store.commit('changTxt', this.obj)
 }
 }
}
</script>

到这里这个demo就结束了,

使用Vuex的案例分析

感觉整个个过程就是一个传输数据的过程,有点类似全局变量,但是vuex是响应式的。

这里当然并没有完全发挥出全部的vuex。

感谢各位的阅读!关于“使用Vuex的案例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

--结束END--

本文标题: 使用Vuex的案例分析

本文链接: https://www.lsjlt.com/news/77604.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作