vue中传值的方式有?
1.父子组件
父组件-->子组件,通过子组件的自定义属性:props
子组件-->父组件,通过自定义事件:this.$emit('事件名',参数1,参数2,...);
2.非父子组件或父子组件
通过数据总数Bus,this.$root.$emit('事件名',参数1,参数2,...)
vuex主要组成部分 (vuex 是更好非父子传值方法)
- 1.state (类似存储全局变量的数据)
- 2.getters (提供用来获取state数据的方法类似于 Vue 中的 计算属性(可以认为是 store 的计算属性),getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。)
- 3.actions (提供跟后台接口打交道的方法,并调用mutations提供的方法) (Action 提交的是 mutation,而不是直接变更状态。)
- 4.mutations (提供存储设置state数据的方法)(处理数据的唯一途径,state的改变或赋值只能在这里)
只是做简单的数据修改(例如n++),它没有涉及到数据的处理,没有用到业务逻辑或者异步函数,可以直接调用mutations里的方法修改数据。
具体使用
如果我们项目中需要组件之间传递值的时候 在项目下单独建立一个store-index.JS
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
let store = new Vuex.Store({
// 1. state
state:{
ceshi:"説過"
},
// // 2. getters
getters:{
// 参数列表state指的是state数据
getCityFn(state){
return state.ceshi;
}
},
// 3. actions
// 通常跟api接口打交道
actions:{
setsgName({commit,state}, name){
// 跟后台打交道
// 调用mutaions里面的方法
commit("setsg", name);
}
},
// 4. mutations
mutations:{
// state指的是state的数据
// name传递过来的数据
setsg(state, name){
state.ceshi = name;//将传参设置给state的ceshi
}
}
});
export default store;
- 在main.js 引入导出的store
import store from './store/store.js';
- 組件中如何使用
(组件页面中的city数据通过this.$store.getters来获取store.js所写getters提供的方法)
<template>
<div class="home">
<h1>{{ceshi}}</h1>
<!-- 按钮导航 -->
<ul>
<li v-for="(item,index) in shuiguoArr" @click="whosg(index)">
<h2>{{item}}</h2>
</li>
</ul>
</div>
</template>
<script>
export default {
data () {
return {
shuiguoArr:['蘋果','香蕉','橘子']
}
},
methods:{
whosg : function(index){
// 调用vuex的ations setsgName
this.$store.commit("setsg", this.shuiguoArr[index]);
///this.$store.dispatch("setsgName", this.shuiguoArr[index]) // 通过异步方法
}
},
computed:{
ceshi:function() {
// 通过vuex的getters方法来获取state里面的数据
return this.$store.getters.getCityFn
}
}
}
</script>
vuex 辅助函数
- mapState (mapState:把state属性映射到computed身上) import {mapGetters,mapMutations,mapState,mapAction} from 'vuex'
computed:{
// this.$store.state.n
...mapState({
n:state=>state.n
'n'
})
}
- mapGetters (mapGetters:把getters属性映射到computed身上)(当state中的属性发生改变的时候就会 触发getters里面的方法)
// this.$store.getters.getCityFn
...mapGetters(["getCityFn"])
- mapActions
methods: {
// 将this.add映射成 this.$store.dispatch('add')
...mapActions(['add']), add mapActions下方法
methodB () {
this.$store.dispatch('add',1) => this.add(1)
}
}
- mapMutations
methods: {
// 将this.add映射成 this.$store.commit('add')
...mapMutations(['add']),
methodA () {
this.$store.commit('add',1) => this.add(1)
}
}