vue中传值的方式有?vue
父组件-->子组件,经过子组件的自定义属性:props
复制代码
子组件-->父组件,经过自定义事件:this.$emit('事件名',参数1,参数2,...);
复制代码
经过数据总数Bus,this.$root.$emit('事件名',参数1,参数2,...)
复制代码
只是作简单的数据修改(例如n++),它没有涉及到数据的处理,没有用到业务逻辑或者异步函数,能够直接调用mutations里的方法修改数据。vuex
若是咱们项目中须要组件之间传递值的时候 在项目下单独创建一个store-index.JSapi
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;
复制代码
import store from './store/store.js';
复制代码
<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 辅助函数缓存
import {mapGetters,mapMutations,mapState,mapAction} from 'vuex'markdown
computed:{
// this.$store.state.n
...mapState({
n:state=>state.n
'n'
})
}
复制代码
// this.$store.getters.getCityFn
...mapGetters(["getCityFn"])
复制代码
methods: {
// 将this.add映射成 this.$store.dispatch('add')
...mapActions(['add']), add mapActions下方法
methodB () {
this.$store.dispatch('add',1) => this.add(1)
}
}
复制代码
methods: {
// 将this.add映射成 this.$store.commit('add')
...mapMutations(['add']),
methodA () {
this.$store.commit('add',1) => this.add(1)
}
}
复制代码