您好,欢迎来到乐天情感。
搜索
您的当前位置:首页如何使用Vuex实现计数器功能

如何使用Vuex实现计数器功能

来源:乐天情感
 这篇文章主要为大家详细介绍了Vuex实现计数器以及列表展示效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本篇教程将以计数器及列表展示两个例子来讲解Vuex的简单用法。

本案例github

从安装到启动初始页面的过程都直接跳过。注意安装时选择需要路由。

首先,src目录下新建store目录及相应文件,结构如下:

index.js文件内容:

src下的main.js里注册store

components文件夹内新建Num.vue组件,内容如下

<template>
 <p>
 <input type="button" value="+" @click="incr" />
 <input type="text" id="input" v-model="count"/>
 <input type="button" value="-"/>
 <br/>
 <router-link to="/list">列表demo</router-link>
 </p>
</template>

<script>
 import store from '../store'
 export default {

 computed:{
 count:{
 get:function () {
 return store.state.count
 },
 set:function (val) {
 store.state.count = val
 }
 }
 },

 methods:{
 incr(){
 // store.commit("increment")
 store.commit("increment") //触发修改
 }
 }
 }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

router文件夹内配置路由:

完成后启动,即可看到结果。计数器演示完成。

现在开始列表演示。

src目录下新建api文件夹,再新建api文件。

api/cover.js:

修改store/modules/cover.js:(定义数据模型)

store内的index.js中注册数据模型:

components文件夹内新建List.vue组件,内容如下:

<template>
 <p class="list">
 <ul>
 <li v-for="cover in covers" @click="removeCover(cover)">
 {{cover.title}}
 </li>
 </ul>
 <p>
 {{covers}}
 </p>
 <h2>请尝试点击li。</h2>
 <router-link to="/num">计数器demo</router-link>

 </p>
</template>

<script>
import {mapGetters,mapActions} from 'vuex';

export default {
 computed:mapGetters({
 covers:"allCover" //利用module的getter获得数据
 }),

 methods:mapActions([
 'removeCover' //利用module的action删除数据
 ]),

 created(){
 this.$store.dispatch('getAllCover') //调用cover数据模型的getAllCover action 用来初始化列表数据。
 }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
 .list{
 text-align: left;
 }
</style>

路由中注册新组件:

完成后访问http://localhost:8080/#/list,即可看到结果。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

vue iview组件表格 render函数的使用方法详解

nodejs实现解析xml字符串为对象的方法示例

微信小程序实现换肤功能

Copyright © 2019- ltcredit.com 版权所有

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务