Vuex实现计数器以及列表展示效果
前端之家收集整理的这篇文章主要介绍了
Vuex实现计数器以及列表展示效果,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_403_0@本篇教程将以计数器及列表展示两个例子来讲解Vuex的简单用法。
@H_
403_0@本案例<a rel="
nofollow" target="_blank" href="
https://github.com/axel10/Vuex_demo-Counter-and-list">github
@H_
403_0@从安装到启动初始
页面的过程都直接跳过。注意安装时选择需要路由。
@H_
403_0@首先,src目录下新建store目录及相应
文件,结构如下:
@H_
403_0@

@H_
403_0@index.js
文件内容:
<div class="jb51code">
<pre class="brush:js;">
import Vue from "vue"
import Vuex from 'vuex'
Vue.use(Vuex); //务必在new Vuex.Store之前use一下
export default new Vuex.Store({
state:{
count:0 //计数器的count
},mutations:{
increment(state){
state.count++
}
}
})
@H_
403_0@src下的main.js里
注册store
注册store
components: { App },template: '
'
});
@H_
403_0@components
文件夹内新建Num.vue组件,
内容如下
@H_
403_0@router
文件夹内配置路由:
Vue.use(Router)
export default new Router({
routes: [
{
path:'/num',component:Num
},{
path:"*",redirect:"/num"
}
]
})
@H_
403_0@完成后启动,即可看到结果。计数器演示完成。
@H_
403_0@现在开始列表演示。
@H_
403_0@src目录下新建api
文件夹,再新建api
文件。
@H_
403_0@

@H_
403_0@api/cover.js:
export default {
getCover(cb) {
setTimeout(() => cb(_cover),100);
/
$.get("/api/data",function (data) {
console.log(data);
})/
},}
@H_
403_0@
修改store/modules/cover.js:(定义数据模型)
const state = {
all:[]
};
const getters={
allCover:state=>state.all //getter用来提供访问接口
};
const actions = {
getAllCover({commit}){
cover.getCover(covers=>{
commit('setCover',covers) //触发setCover修改。
})
},removeCover({commit},cover){
commit('removeCover',cover)
}
};
const mutations = { //mutations用来修改state。
setCover(state,covers){
state.all = covers
},removeCover(state,cover){
console.log(cover.id);
state.all = state.all.filter(function (OCover) {
return OCover.id !== cover.id
})
}
};
export default {
state,getters,actions,mutations
}
@H_
403_0@store内的index.js中
注册数据模型:
Vue.use(Vuex); //务必在new Vuex.Store之前use一下
export default new Vuex.Store({
modules:{
cover //注册cover数据模型
},state:{
count:0 //计数器的count
},mutations:{
increment(state){
state.count++
}
}
})
@H_
403_0@components
文件夹内新建List.vue组件,
内容如下:
@H_403_0@
{{covers}}
请尝试点击li。
@H_
403_0@路由中
注册新组件:
Vue.use(Router)
export default new Router({
routes: [
{
path:'/num',{
path:'/list',component:List
},redirect:"/num"
}
]
})
@H_
403_0@完成后访问http://localhost:8080/#/list,即可看到结果。
@H_
403_0@以上就是本文的全部
内容,希望对大家的学习有所帮助,也希望大家多多
支持编程之家。