一、vuex案例-搭建黑马头条项目
接下来,通过一个案例来使用Vuex介入我们的数据管理
通过vue-cli脚手架搭建项目
$ vue create toutiao #创建项目
选择 vuex / eslint(stanadard) / pre-cssprocesser (less) 确定
在main.js中引入样式(该样式在资源/vuex样式中,拷贝到styles目录下)
import './styles/index.css'
拷贝图片资源到assets目录下
1.首先关闭eslint
2.如果不行的话加上如下配置
.eslintrc.js文件的rules下面加上这两句代码就不会报错了 没有这个文件就自己创建一个!!!!
'vue/multi-word-component-names': 'off',
'space-before-function-paren': 0
//.eslintrc.js文件
module.exports = {
root: true,
env: {
node: true
},
extends: ['plugin:vue/essential', '@vue/standard'],
parserOptions: {
parser: '@babel/eslint-parser'
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'vue/multi-word-component-names': 'off',
'space-before-function-paren': 0
}
}
3.在App.vue中拷贝基本结构
<div id="app">
<ul class="catagtory">
<li class='select'>开发者资讯</li>
<li>ios</li>
<li>c++</li>
<li>android</li>
<li>css</li>
<li>数据库</li>
<li>区块链</li>
<li>go</li>
<li>产品</li>
<li>后端</li>
<li>linux</li>
<li>人工智能</li>
<li>php</li>
<li>javascript</li>
<li>架构</li>
<li>前端</li>
<li>python</li>
<li>java</li>
<li>算法</li>
<li>面试</li>
<li>科技动态</li>
<li>js</li>
<li>设计</li>
<li>数码产品</li>
<li>html</li>
<li>软件测试</li>
<li>测试开发</li>
</ul>
<div class="list">
<div class="article_item">
<h3 class="van-ellipsis">python数据预处理 :数据标准化</h3>
<div class="img_box">
<img src="@/assets/back.jpg"
class="w100" />
</div>
<!---->
<div class="info_box">
<span>13552285417</span>
<span>0评论</span>
<span>2018-11-29T17:02:09</span>
</div>
</div>
</div>
</div>
二、vuex案例-封装分类组件和频道组件
为了更好的区分组件之间的职责,我们将上方的频道和下方的列表封装成不同的组件
components/catagtory.vue
<template>
<ul class="catagtory">
<li class='select'>开发者资讯</li>
<li>ios</li>
<li>c++</li>
<li>android</li>
<li>css</li>
<li>数据库</li>
<li>区块链</li>
<li>go</li>
<li>产品</li>
<li>后端</li>
<li>linux</li>
<li>人工智能</li>
<li>php</li>
<li>javascript</li>
<li>架构</li>
<li>前端</li>
<li>python</li>
<li>java</li>
<li>算法</li>
<li>面试</li>
<li>科技动态</li>
<li>js</li>
<li>设计</li>
<li>数码产品</li>
<li>html</li>
<li>软件测试</li>
<li>测试开发</li>
</ul>
</template>
components/new-list.vue
<template>
<div class="list">
<div class="article_item">
<h3 class="van-ellipsis">python数据预处理 :数据标准化</h3>
<div class="img_box">
<img src="@/assets/back.jpg"
class="w100" />
</div>
<!---->
<div class="info_box">
<span>13552285417</span>
<span>0评论</span>
<span>2018-11-29T17:02:09</span>
</div>
</div>
</div>
</template>
在App.vue中引入并使用
<template>
<!-- app.vue是根组件 -->
<div id="app">
<catagtory />
<new-list />
</div>
</template>
<script>
import Catagtory from './components/catagtory'
import NewList from './components/new-list'
export default {
components: {
Catagtory, NewList
}
}
</script>
三、vuex案例-在vuex中加载分类和频道数据
1.安装请求数据的工具 axios
$ yarn add axios
接口
黑马头条项目接口问题
- 更换后的接口基础地址:baseURL:http://toutiao.itheima.net
- 课程视频中的项目接口地址:baseURL: http://ttapi.research.itcast.cn
- 新版接口文档地址:http://toutiao.itheima.net/api.html
获取频道列表
http://toutiao.itheima.net/v1_0/channels
获取频道的新闻信息
http://toutiao.itheima.net/v1_0/articles?channel_id=${cataId}×tamp=${Date.now()}&with_top=1
设计categtory和newlist的vuex模块
我们采用模块化的管理模式,建立一个专门的模块来管理分类和新闻数据
2.在store目录下新建目录modules, 新建 catagtory.js和newlist.js
模块结构
export default {
namespaced: true,
state: {},
mutations: {},
actions: {}
}
3.在store/index.js中引入定义的两个模块
这就类似于导出js文件了
import catagtory from './modules/catagtory'
import newlist from './modules/newlist'
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
catagtory,
newlist
}
})
分类模块下设置分类数组和当前激活分类
3.在catagtory.js的 state中定义分类频道列表和当前激活
state: {
// 存放分类数组的属性
catagtory: [],
currentCatagtory: '' // 当前激活的分类
}
4.定义更新频道列表的mutations
同步操作修改state
mutations: {
// 会认为载荷是要更新的数组
updateCatagtory (state, payload) {
state.catagtory = payload // 更新分类数据
// 赋值分类
},
// 更新当前的激活分类
updateCurrentCatagtory (state, payload) {
state.currentCatagtory = payload
}
}
5.通过getters建立对于子模块的快捷访问
类似于计算属性,注意下面是写在store/index.js文件里面的
通过getters建立对于数据的快捷访问
建立对于子模块的快捷访问 state.模块名称
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
catagtory,
newlist
},
getters: {
catagtory: state => state.catagtory.catagtory, // 建立快捷访问
currentCatagtory: state => state.catagtory.currentCatagtory
}
})
遍历分类数据并判断激活class
注意点MAP的使用方法扩展运算符
使用扩展运算符,将导出的状态映射给计算属性。由于mapState模块映射出来的类型是对象,因此需要将对象里面的东西展开出来,否则就是对象套一个对象,在computed中是不行的。
但是当你有任何本地计算属性时,你需要扩展语法。这是因为mapGetters返回一个对象。然后,我们需要对象扩展运算符来将多个对象合并为一个对象。
6.分类组件遍历vuex数据
在catagtory.vue中使用getters
import { mapGetters } from 'vuex'
computed: {
...mapGetters(['catagtory', 'currentCatagtory'])
},
catagtory.vue修改为
<ul class="catagtory">
<li :class="{ select: currentCatagtory === item.id }" v-for="item in catagtory" :key="item.id">{{ item.name }}</li>
</ul>
封装调用获取分类action,激活第一个分类
7.定义获取频道列表的action, 将第一个频道激活
在catagtory.js异步action 激活分类
// 异步action 激活分类
actions: {
async getCatagtory(context) {
const {
// promise
// async/await
// axios 默认包了一层data的数据结构
data: {
data: { channels }
}
} = await axios.get('http://toutiao.itheima.net/v1_0/channels')
// console.log(channels)
// 需要通过mutation才能修改state
context.commit('updateCatagtory', channels)
context.commit('updateCurrentCatagtory', channels[0].id)
}
}
这样还是不能使用的,因为只定义action没有调用action,需要在catagtory.vue当前的生命周期中调用子模块action 【index.js 的子模块的action】
8.初始化catagtory时调用action
catagtory.vue
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(['catagtory'])
},
created () {
// 调用子模块的actions
this.$store.dispatch('catagtory/getCatagtory')
}
}
9.点击分类时,触发分类切换
直接更新当前激活分类mutaions ,传载荷,有锁需要传路径
<li @click="$store.commit('catagtory/updateCurrentCatagtory', item.id)" :class="{ select: currentCatagtroy === item.id }" v-for="item in catagtory" :key="item.id">{{ item.name }}</li>
定义新闻数据,并封装获取新闻的Action
10…在newlist.js中定义获取头条内容的数据
state: {
allData: {}
// 放置的是所有的数据 { 分类id: 列表1, 分类id:列表2 }
}
11.定义更新头条内容的mutations
mutations: {
// payload 载荷 { 1: [], 2: [], 3: [], 4}
updateList (state, { currentCatagtory, list }) {
// 不是响应式的
// state.allData[currentCatagtory] = list // 这样做事大错特错第 感觉不到变化 就不会通知组件
state.allData = { ...state.allData, [currentCatagtory]: list }
// 没写后面就是浅拷贝 写了更新的类会被替换
// 这句代码的含义 就相当于 在一个新的对象后面追加了一个属性 更新某个属性的内容
}
},
12.定义根据分类标识获取新闻的action
actions: {
// 获取新闻列表数据
// 分类id只能通过传递的方式传进来
async getNewList (context, cataId) {
const { data: { data: { results } } } = await axios.get(`http://toutiao.itheima.net/v1_0/articles?channel_id=${cataId}×tamp=${Date.now()}&with_top=1`)
// results是新闻列表
context.commit('updateList', { currentCatagtory: cataId, list: results })
}
}
此时alldata还是空的 打开路浏览器vue发现里面呢数据也还是空的 获取新闻列表数据 激活的时候拿到数据,监听当前页
监听激活分类,触发获取新闻Action
13.在new-list组件中,引入当前分类的id,监视其改变,一旦改变,触发获取新闻的action
import { mapGetters } from 'vuex'
export default {
// 引入当前分类的id,监视其改变,一旦改变,触发获取新闻的action
computed: {
...mapGetters(['currentCatagtory'])
},
watch: {
// newValue是当前最新的激活的id
currentCatagtory (newValue) {
// 最新的id 异步 加了锁加路径
this.$store.dispatch('newlist/getNewList', newValue)
}
}
}
这样操作后,控制台vue里面就有数据了
// ...mapGetters(['currentCatagtroy'])
这里字母拼错了,一定要非常注意这个字母就不会报错了!!!
处理显示新闻内容的数据
14.定义当前显示列表的getters
index,js文件里面如下
getters: {
currentList: state => state.newlist.allData[state.catagtory.currentCatagtory] || []
}
15.修改new-list内容
<template>
<div class="list">
<div class="article_item" v-for="item in currentList" :key="item.art_id">
<h3 class="van-ellipsis">{{ item.title }}</h3>
<div class="img_box" v-if="item.cover.type === 1">
<img :src="item.cover.images[0]"
class="w100" />
</div>
<div class="img_box" v-else-if="item.cover.type === 3">
<img :src="item.cover.images[0]"
class="w33" />
<img :src="item.cover.images[1]"
class="w33" />
<img :src="item.cover.images[2]"
class="w33" />
</div>
<!---->
<div class="info_box">
<span>{{ item.aut_name }}</span>
<span>{{ item.comm_count }}评论</span>
<span>{{ item.pubdate }}</span>
</div>
</div>
</div>
</template>
<script>
// 引入当前激活的分类id
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(['currentCatagtory', 'currentList'])
},
watch: {
currentCatagtory (newValue) {
// newValue是当前最新的激活的id
this.$store.dispatch('newlist/getNewList', newValue)
}
}
}
</script>
<style>
</style>