1⃣️.子组件标签绑定须要传递的参数名 2⃣️.子组件页面使用props 接收参数
1⃣️.子组件使用$emit来触发一个自定义事件,并传递一个参数 2⃣️.父组件中的子标签中监听该自定义事件并添加一个响应该事件的处理方法
总线/观察者模式javascript
公共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>
方式1:query传值在router-link标签内to的后面直接加 方式2:params传值:在router-link中加
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>