学做美食看哪个网站,产品互联网营销推广,佛山网站建设开发,扬州网站开发公司电话代码下载
Vuex 概述
组件之间共享数据的方式#xff1a;
父组件向子组件传值#xff0c;是以属性的形式绑定值到子组件#xff08;v-bind#xff09;#xff0c;然后子组件用属性props接收。子组件向父组件传值#xff0c;子组件用 $emit() 自定义事件#xff0c;父组…代码下载
Vuex 概述
组件之间共享数据的方式
父组件向子组件传值是以属性的形式绑定值到子组件v-bind然后子组件用属性props接收。子组件向父组件传值子组件用 $emit() 自定义事件父组件用v-on监听子组件的事件。兄弟组件的传值通过事件中心传递数据提供事件中心 var hub new Vue()传递数据方通过一个事件触发 hub.$emit(方法名传递的数据)接收数据方通过在 mounted(){} 钩子中 触发 hub.$on(方法名, 传递的数据)。
Vuex是实现组件全局状态数据管理的一种机制可以方便的实现组件之间的数据共享。使用Vuex管理数据的好处
能够在vuex中集中管理共享的数据便于开发和后期进行维护能够高效的实现组件之间的数据共享提高开发效率存储在vuex中的数据是响应式的当数据发生改变时页面中的数据也会同步更新
一般情况下只有组件之间共享的数据才有必要存储到 vuex 中对于组件中的私有数据依旧存储在组件自身的 data 中即可。
Vuex 简单使用
1、安装 vuex 依赖包
npm install vuex --save2、导入 vuex 包
import Vuex from vuex
Vue.use(Vuex)3、创建 store 对象
const store new Vuex.Store({// state 中存放的就是全局共享的数据state: { count: 0 }
})4、 将 store 对象挂载到 vue 实例中
new Vue({el: #app,render: h h(app),// 将创建的共享数据对象挂载到 Vue 实例中// 所有的组件就可以直接从 store 中获取全局的数据了store
})在使用 vue 脚手架创建项目时可以在功能选项中直接开启使用 Vuex 的开关。
Vuex 的核心概念
Vuex 中的主要核心概念如下StateMutationActionGetter。
State
State 提供唯一的公共数据源所有共享的数据都要统一放到 Store 的 State 中进行存储。
// 创建store数据源提供唯一公共数据
const store new Vuex.Store({state: { count: 0 }
})组件访问 State 中数据的第一种方式this.$store.state.全局数据名称
组件访问 State 中数据的第二种方式 1、从 vuex 中按需导入 mapState 函数
import { mapState } from vuex2、通过刚才导入的 mapState 函数将当前组件需要的全局数据映射为当前组件的 computed 计算属性
computed: {...mapState([count])
}Mutation
Mutation 用于变更 Store中 的数据。
注意只能通过 mutation 变更 Store 数据不可以直接操作 Store 中的数据。通过这种方式虽然操作起来稍微繁琐一些但是可以集中监控所有数据的变化。
定义 Mutation也可以在触发 mutations 时传递参数
export default new Vuex.Store({state: {count: 0},mutations: {add(state) {state.count},addN(state, step) {state.count step}}
})组件触发 mutations 的第一种方式this.$store.commit(add) 、 this.$store.commit(add, 3)。
组件触发 mutations 的第二种方式 1、从 vuex 中按需导入 mapMutations 函数
import { mapMutations } from vuex2、通过刚才导入的 mapMutations 函数将需要的 mutations 函数映射为当前组件的 methods 方法
methods: {...mapMutations([add, addN])
}Action
Action 用于处理异步任务。如果通过异步操作变更数据必须通过 Action而不能使用 Mutation但是在 Action 中还是要通过触发 Mutation 的方式间接变更数据。
定义 Action也可以在触发 actions 异步任务时携带参数 actions: {addAsync(context) {setTimeout(() {context.commit(add)}, 1000);},addNAsync(context, step) {setTimeout(() {context.commit(addN, step)}, 1000);}}触发 actions 的第一种方式this.$store.dispatch(addSsync)、this.$store.dispatch(addAsync, 3)。
触发 actions 的第二种方式 1、从 vuex 中按需导入 mapActions 函数
import { mapActions } from vuex2、通过刚才导入的 mapActions 函数将需要的 actions 函数映射为当前组件的 methods 方法
methods: {...mapActions([addASync, addNASync])
}Getter
Getter 用于对 Store 中的数据进行加工处理形成新的数据类似 Vue 的计算属性。Store 中数据发生变化Getter 的数据也会跟着变化。
定义 Getter
export default new Vuex.Store({state: {count: 0},getters: {showNum(state) {return 当前最新数量是 state.count}}
}使用 getters 的第一种方式this.$store.getters.showNum。
使用 getters 的第二种方式 1、从 vuex 中按需导入 mapGetters 函数
import { mapGetters } from vuex2、通过刚才导入的 mapGetters 函数将需要的 getters 函数映射为当前组件的 computed 计算属性
computed: {...mapGetters([showNum])
}示例
1、在 store index.js 中创建 store 对象并定义相应的 state、mutations、actions、getters
import Vue from vue
import Vuex from vuexVue.use(Vuex)export default new Vuex.Store({state: {count: 0},getters: {showNum(state) {return 当前最新数量是 state.count}},mutations: {add(state) {state.count},addN(state, step) {state.count step},sub(state) {state.count--},subN(state, step) {state.count - step}},actions: {addAsync(context) {setTimeout(() {context.commit(add)}, 1000);},addNAsync(context, step) {setTimeout(() {context.commit(addN, step)}, 1000);},subAsync(context) {setTimeout(() {context.commit(sub)}, 1000);},subNAsync(context, step) {setTimeout(() {context.commit(subN, step)}, 1000);}},modules: {}
})2、在 components addition.vue 文件中运用第一种方法使用 state、mutations、actions、getters
templatedivh3计算结果{{$store.state.count}}/h3button clickbtnHandle11/buttondivinput typenumber placeholder请输入数值 v-model.numberaddNumbutton clickbtnHandleN{{addNum}}/button/divbutton clickbtnHandle1Async1 async/buttondivinput typenumber placeholder请输入数值 v-model.numberaddNumAsyncbutton clickbtnHandleNAsync{{addNumAsync}}/button/divh3{{$store.getters.showNum}}/h3/div
/templatescript
export default {data() {return {addNum: 2,addNumAsync: 3}},methods: {btnHandle1() {this.$store.commit(add)},btnHandleN() {this.$store.commit(addN, this.addNum)},btnHandle1Async() {this.$store.dispatch(addAsync)},btnHandleNAsync() {this.$store.dispatch(addNAsync, this.addNumAsync)}}
}
/script3、在 components subtraction.vue 文件中运用第二种方法使用 state、mutations、actions、getters
templatedivh3计算结果{{count}}/h3button clickbtnHandle1-1/buttondivinput typenumber placeholder请输入数值 v-model.numbersubNumbutton clickbtnHandleN-{{subNum}}/button/divbutton clicksubAsync-1 async/buttondivinput typenumber placeholder请输入数值 v-model.numbersubNumAsyncbutton clicksubNAsync(subNumAsync)-{{subNumAsync}} async/button/divh3{{showNum}}/h3/div
/templatescript
import { mapState, mapMutations, mapActions, mapGetters } from vuex;
export default {data() {return {subNum: 2,subNumAsync: 3}},computed: {...mapState([count]),...mapGetters([showNum])},methods: {...mapMutations([sub, subN]),btnHandle1() {this.sub()}, btnHandleN() {this.subN(this.subNum)},...mapActions([subAsync, subNAsync])}
}
/scriptVuex 案例
项目初始化
1、通过 vue ui 命令打开可视化面板创建新项目略这里使用的是和上面示例同一个项目。
2、安装依赖包npm install axios、npm install ant-design-vue1.7.8因为这里使用的 vue2.x所以 ant-design-vue 版本使用1.7.8。
注意需要在 package.json 文件中将 eslint-plugin-vue 版本改为7.0.0 eslint-plugin-vue: ^7.0.0否则会与 ant-design-vue 有版本冲突。
打开 main.js 导入并配置相应的组件库
// 1. 导入 ant-design-vue 组件库
import Antd from ant-design-vue
// 2. 导入组件库的样式表
import ant-design-vue/dist/antd.css
// 3. 安装组件库
Vue.use(Antd)3、实现 Todos 基本布局在 components 文件夹中新建 toDoList.vue 文件并实现布局代码
templatediv idappa-input placeholder请输入任务 classmy_ipt /a-button typeprimary添加事项/a-buttona-list bordered :dataSourcelist classdt_lista-list-item slotrenderItem slot-scopeitem!-- 复选框 --a-checkbox{{item.info}}/a-checkbox!-- 删除链接 --a slotactions删除/a/a-list-item!-- footer区域 --div slotfooter classfooter!-- 未完成的任务个数 --span0条剩余/span!-- 操作按钮 --a-button-groupa-button typeprimary全部/a-buttona-button未完成/a-buttona-button已完成/a-button/a-button-group!-- 把已经完成的任务清空 --a清除已完成/a/div/a-list/div
/templatescript
export default {name: app,data() {return {list: [{id: 0,info: Racing car sprays burning fuel into crowd.,done: false},{ id: 1, info: Japanese princess to wed commoner., done: false },{id: 2,info: Australian walks 100km after outback crash.,done: false},{ id: 3, info: Man charged over missing wedding girl., done: false },{ id: 4, info: Los Angeles battles huge wildfires., done: false }]}}
}
/scriptstyle scoped
#app {padding: 10px;
}.my_ipt {width: 500px;margin-right: 10px;
}.dt_list {width: 500px;margin-top: 10px;
}.footer {display: flex;justify-content: space-between;align-items: center;
}
/style功能实现
动态加载任务列表数据
1、打开public文件夹创建一个list.json文件填充数据
[{id: 0,info: Racing car sprays burning fuel into crowd.,done: false},{id: 1,info: Japanese princess to wed commoner.,done: false},{id: 2,info: Australian walks 100km after outback crash.,done: false},{id: 3,info: Man charged over missing wedding girl.,done: false},{id: 4,info: Los Angeles battles huge wildfires.,done: false}
]2、再接着打开 store/index.js导入 axios 并在 actions 中添加 axios 请求 json 文件获取数据的代码因为数据请求是异步的所以必须在 actions 中实现如下
import axios from axiosexport default new Vuex.Store({state: {// 任务列表list: []},mutations: {initList(state, list) {state.list list}},actions: {getList(context) {axios.get(/list.json).then(({ data }) {console.log(data: , data);context.commit(initList, data)})}}
})3、打开 toDoList.vue 文件将 store 中的数据获取并展示
script
import { mapState } from vuexexport default {data() {return {// list:[]}},created(){// console.log(this.$store);this.$store.dispatch(getList)},computed:{...mapState([list])}
}
/script文本框与store数据的双向同步
1、在 store/index.js 文件的 state 中新增 inputValue: aaa 字段并在 mutations 中新增其修改方法 setInputValue // 设置 输入值setInputValue(state, value) {console.log(value: , value);state.inputValue value}2、在 toDoList.vue 文件的 computed 中映射 inputValue 计算方法 computed:{...mapState([list, inputValue])}3、将 inputValue 计算方法绑定到 a-input 元素的 value 上。
4、为 a-input 元素绑定 change 事件方法 handleInputChange handleInputChange(e) {this.setInputValue(e.target.value)}添加任务
1、在 store/index.js 文件 state 中新增 nextId: 5 字段并在 mutations 中编写 addItem // 添加任务项addItem(state) {const item {id: state.nextId,info: state.inputValue.trim(),done: false}state.list.push(item)state.nextIdstate.inputValue }2、在 toDoList.vue 文件给“添加事项”按钮绑定点击事件编写处理函数 addItemToList() {console.log(iv: , this.inputValue.trim());if (this.inputValue.trim().length 0) {return this.$message.warning(文本框内容不能为空)}this.$store.commit(addItem)}其他功能实现
store/index.js 文件代码具体实现
export default new Vuex.Store({state: {// 任务列表list: [],// 文本框内容inputValue: aaa,nextId: 5,viewKey: all},getters: {infoList(state) {if (state.viewKey all) {return state.list} else if (state.viewKey undone) {return state.list.filter(item !item.done)} else {return state.list.filter(item item.done)}},unDoneLength(state) {return state.list.filter(item !item.done).length}},mutations: {// 修改列表数据initList(state, list) {state.list list},// 设置 输入值setInputValue(state, value) {console.log(value: , value);state.inputValue value},// 添加任务项addItem(state) {const item {id: state.nextId,info: state.inputValue.trim(),done: false}state.list.push(item)state.nextIdstate.inputValue },// 删除任务项removeItem(state, id) {const index state.list.findIndex(item item.id id)if (index ! -1) {state.list.splice(index, 1)}},// 更改任务完成状态statusChange(state, params) {const index state.list.findIndex(item item.id params.id)if (index ! -1) {state.list[index].done params.done}},// 清除完成任务项clearDone(state) {state.list state.list.filter(item !item.done)},// 改版列表数据类型changeViewKey(state, key) {state.viewKey key}},actions: {getList(context) {axios.get(/list.json).then(({ data }) {console.log(data: , data);context.commit(initList, data)})}}
})toDoList.vue 文件具体实现
templatediva-input placeholder请输入任务 classmy_ipt :valueinputValue changehandleInputChange/a-button typeprimary clickaddItemToList添加事项/a-buttona-list bordered :dataSourceinfoList classdt_list a-list-item slotrenderItem slot-scopeitem!-- 复选框 --a-checkbox :checkeditem.done changecbStatusChange(item.id, $event){{item.info}}/a-checkbox!-- 删除链接 --a slotactions clickremoItemById(item.id)删除/a/a-list-item!-- footer区域 --div slotfooter classfooter!-- 未完成的任务个数 --span{{unDoneLength}}条剩余/span!-- 操作按钮 --a-button-groupa-button :typeviewKey all ? primary : default clickchangeList(all)全部/a-buttona-button :typeviewKey undone ? primary : default clickchangeList(undone)未完成/a-buttona-button :typeviewKey done ? primary : default clickchangeList(done)已完成/a-button/a-button-group!-- 把已经完成的任务清空 --a clickclear清除已完成/a/div/a-list/div
/templatescript
import { mapState, mapMutations, mapGetters } from vuex
export default {data() {return {}},created() {this.$store.dispatch(getList)},computed: {...mapState([inputValue, viewKey]),...mapGetters([unDoneLength, infoList])},methods: {...mapMutations([setInputValue]),handleInputChange(e) {this.setInputValue(e.target.value)},addItemToList() {console.log(iv: , this.inputValue.trim());if (this.inputValue.trim().length 0) {return this.$message.warning(文本框内容不能为空)}this.$store.commit(addItem)},// 根据 id 删除对应的任务remoItemById(id) {this.$store.commit(removeItem, id)},cbStatusChange(id, e) {const params {id,done: e.target.checked}console.log(chang params: , params);this.$store.commit(statusChange, params)},// 清除已完成clear() {this.$store.commit(clearDone)},changeList(key) {console.log(changeList: , key);this.$store.commit(changeViewKey, key)}}
}
/script1、删除任务通过 mutations 修改列表数据实现详细实现细节见上述代码。
2、绑定复选框的选中状态同上。
3、修改任务的完成状态同上。
4、清除已完成的任务同上。
5、任务列表数据的动态切换同上。
6、统计未完成的任务的条数通过 Getter 加工列表数实现详细实现细节见上述代码