1.父組件向子組件傳值
1⃣️.子組件標籤綁定需要傳遞的參數名
2⃣️.子組件頁面使用props 接收參數
2.子組件向父組件傳值
1⃣️.子組件使用$emit來觸發一個自定義事件,並傳遞一個參數
2⃣️.父組件中的子標籤中監聽該自定義事件並添加一個響應該事件的處理方法
3.非父子組件進行傳值 要定義個公共的公共實例文件bus.js,作爲中間倉庫來傳值,不然路由組件之間達不到傳值的效果。
總線/觀察者模式
公共bus.js
//bus.js import Vue from 'vue'
export default new Vue()
組件A:
<template>
<div> A組件: <span>{{elementValue}}</span> <input type="button" value="點擊觸發" @click="elementByValue">
</div>
</template>
<script> // 引入公共的bug,來做爲中間傳達的工具
import Bus from './bus.js'
export default {
data () {
return { elementValue: 4 } },
methods: {
elementByValue: function () {
Bus.$emit('val', this.elementValue) }
} }
</script>
組件B:
<template>
<div> B組件: <input type="button" value="點擊觸發" @click="getData">
<span>{{name}}</span>
</div>
</template>
<script>
import Bus from './bus.js'
export default {
data () {
return { name: 0 }
},
mounted: function () {
var vm = this // 用$on事件來接收參數
Bus.$on('val', (data) => {
console.log(data) vm.name = data })
},
methods: {
getData: function () { this.name++ }
}
}
</script>
4.頁面跳轉傳值
方式1:query傳值在router-link標籤內to的後面直接加
方式2:params傳值:在router-link中加
5.vuex 全局管理狀態
import Vue from 'vue'
import Vuex from 'vuex'
// 首先聲明一個狀態 state
const state = {
msg: ''
}
// 然後給 actions 註冊一個事件處理函數,當這個函數被觸發時,將狀態提交到 mutaions中處理
const actions = {
saveName({commit}, msg) {
commit('saveMsg', msg) // 提交到mutations中處理
}
}
// 更新狀態
const mutations = {
saveMsg(state, msg) {
state.msg = msg;
}
}
// 獲取狀態信息
const getter = {
showState(state) {
console.log(state.msg)
}
}
// 下面這個相當關鍵了,所有模塊,記住是所有,註冊才能使用
export default new Vuex.Store({
state,
getter,
mutations,
actions
})
步驟2:在子組件中使用(保存輸入)
具體到我這裏,是在c-form中使用它:
<template>
<div>
<input type="text" @blur=saveName(username) v-model="username" placeholder="Your name">
</div>
</template>
<script type="text/javascript">
// 引入mapActions,很重要
import { mapActions } from 'vuex'
export default {
data() {
return {
username:'',
password: ''
}
},
methods: {
...mapActions({
// 在input 的blur 事件中觸發回調,並將輸入值作爲參數返回到store中
saveName: 'saveName'
})
}
}
</script>
步驟3:獲取在步驟2 中的輸入值(獲取state)
<template>
<div id="login">
<c-header></c-header>
<c-form></c-form>
<p class="content-block"><a href="javascript:;" @click=showState class="button button-fill button-success">登錄</a></p>
</div>
</template>
<script>
// 引入mapGtters,很重要
import { mapGetters } from 'vuex'
export default {
methods: {
...mapGetters([
// 在store.js 中註冊的getters
'showState'
])
},
components: {
"c-form": require('../components/form.vue'),
"c-header": require('../components/header.vue')
}
}
</script>