Vue-CLI与Vuex使用方法实例分析
本文实例讲述了Vue-CLI与Vuex使用方法。分享给大家供大家参考,具体如下:
1、通过Vue-CLI创建项目
- build文件夹:存放构建项目所需的文件
- config文件夹:项目的设置文件
- index.js:设置路径、跨域代理、服务器、端口号等
- node_modules文件夹:安装依赖的文件
- src文件夹
- assets文件夹:存放页面相关的静态文件例如CSS
- components文件夹:存放页面使用的公共组件
- router/index.js:设置访问路径所对应的页面
- views文件夹:存放vue页面文件
- app.vue:页面主入口组件
- main.js:页面主js入口
- static文件夹:存放静态资源如图片等
- index.html:主页面
- package.json:项目所使用的依赖列表
2、Vuex核心概念
console.log(store.state.count)
conststore=newVuex.Store({ state:{ count:0 }, mutations:{ increment(state){ state.count++ } } })
store.commit('increment')
actions:{ incrementAction(context){ context.commit('increment') } } store.dispatch('incrementAction')//通过分发来调用action
综上,vuex的数据流图如下:当vuecomponents触发事件时,引起分发action,action提交到mutation,mutation改变state的值,导致重新渲染vuecomponent组件。
3、使用vuex
1、引入vuex文件或在项目的mian.js中引入并使用
2、实例化Vuex
conststore=newVuex.Store({ state:{ count:10 }, mutations:{ increment(state){//只有通过mutation中的方法才可修改store中的值 state.count++; } } });
3、在app中注册store
letvue=newVue({ el:'#app', data:{ }, store:store })
4、在注册后的vue的组件couter中可以使用store,通过computed属性访问$store.state中的数据:
components:{ counter:{ template:`计数{{count}}`, computed:{ count(){ returnthis.$store.state.count; } } } },
5、组件的add方法通过commit改变store中的值:
methods:{ add(){ this.$store.commit('increment') } }
也可以通过commit进行参数传递:this.$store.commit('increment',num)
6、通过getters得到处理后的数据:
conststore=newVuex.Store({ state:{ count:10 }, getters:{//在getters中对state中的count处理之后输出为square,供外部调用 square(state){ returnstate.count*state.count; } }, mutations:{ increment(state){ state.count++; } } });
通过计算属性square调用$store.getters.square
computed:{ square(){ returnthis.$store.getters.square; } }
希望本文所述对大家vue.js程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。