vue 元件間傳值(個人精編)
阿新 • • 發佈:2018-12-11
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>