小demo----vuex的练习
先来看效果
目标 通过vuex发送请求 渲染页面 代码:
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
bookList: []
},
mutations: {
// 获取图书列表
getBooks (state, newList) {
state.bookList = newList
},
delBook (state, index) {
state.bookList.splice(index, 1)
}
},
actions: {
async ajax (state) {
try {
const { data } = await axios({
url: 'https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/books'
})
this.commit('getBooks', data.data)
} catch (err) {
console.log(err)
}
}
},
modules: {
}
})
async 代表一个异步操作 await用来接受axios发送请求的成功的结果
try catch用来捕获发起请求中的错误
shopCar 组件
<template>
<div class="shop">
<div class="shop-item" v-for="(obj,index) in $store.state.bookList" :key="index">
<i class="el-icon-circle-close" @click="del(index)"></i>
<img :src="obj.img" alt="">
<p>{{obj.name}}</p>
<span>{{obj.price}}</span>
</div>
</div>
</template>
<script>
export default {
created () {
this.$store.dispatch('ajax')
},
methods: {
del (ind) {
this.$store.commit('delBook', ind)
}
}
}
</script>
<style lang="less" scoped>
div{
box-sizing: border-box;
}
.shop{
width: 900px;
margin: 0 auto;
margin-top: 50px;
// background-color: #ccc;
.shop-item{
position: relative;
float: left;
width: 25%;
height: 280px;
// background-color: red;
padding: 20px 27px;
text-align: center;
i{
position: absolute;
display: none;
top: 5px;
right: 2px;
font-size:20px;
color:skyblue
}
img{
width:100%;
height: 75%;
}
p{
padding: 0 !important;
margin: 0;
}
span{
// margin-left: 60px;
text-align: center;
}
}
.shop-item:hover {
box-shadow: 0 8px 8px rgba(10,16,20,.24),0 0 8px rgba(10,16,20,.12);
}
.shop-item:hover i{
cursor: pointer;
display: block;
}
}
</style>
1. 组件初始化钩子函数调用vuex中的action发起ajax请求 拿到数组 循环渲染
2.删除:点击传入索引 调用this.$store.commit('') 调用vuex中的mutation中的方法来对vuex中的state的数据进行修改
app.vue
<template>
<div>
<ShopCar></ShopCar>
</div>
</template>
<script>
import ShopCar from './views/02-购物车渲染.vue'
export default {
name: '',
props: {},
data () {
return {}
},
methods: {},
computed: {},
watch: {},
created () {
},
mounted () {},
components: {
ShopCar
}
}
</script>
<style scoped lang='less'>
</style>
注册组件 显示页面