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)
}
}
複製代碼