There are many ways to transfer parameters between Vue pages and components. The common ways are listed here. Welcome to review and supplement.

One, route parameter transmission

The route here is passed as a programmatic router.push(…) For example, the declarative

Here the simulation scenario is to jump from componentsA. Vue page to componentsB. Vue page. First, the route configuration information is as follows:

router.js

import Vue from 'vue'
import Router from 'vue-router'

import componentsA from './components/componentsA'Vue import componentsB from componentSa. vue import componentsB from'./components/componentsB'// Create componentsb.vue vue. Use (Router)export default new Router({
	routes:[
		{
			path:'/componentsA',
			name:'componentsA',
			component:componentsA
		},
		{
			path:'/componentsB',
			name:'componentsB',
			component:componentsB
		}
	]
})Copy the code

1.1 Route Configuration Parameter Transmission

First determine the parameter name you want to pass, modify the route configuration, pass name,age,sex three parameters:

		{
			path:'/componentsB/:name/:age/:sex',
			name:'componentsB',
			component:componentsB
		}Copy the code

Componentsa. vue configures this.$router. Push parameter to componentSa. vue:

componentsA.vue

<template> <div> <div> I am component A</div> < button@click ='routerToB1'</button> </div> </template> <script>export default{
		data() {return{
				person:{name:'Gene',age:'18',sex:'male'}
			}
		},
		methods: {
			routerToB1() {
				this.$router.push({
					path:`componentsB/${this.person.name}/${this.person.age}/${this.person.sex}`
				})
			}
		},
	}
</script>
<style>
</style>Copy the code

$route. Params (componentsB. Vue);

componentsB.vue

<template> <div> <div> I am component B</div> </div> </template> <script>export default{
		created(){
			this.getRouterData()
		},
		methods: {
			getRouterData(){
				const param = this.$route.params
				console.log(param)//{name:'Gene',age:'18',sex:'male'}
			}
		},
	}
</script>
<style>
</style>Copy the code

{name:’Gene’,age:’18’,sex:’male’}, successfully obtain the parameters from A page. And address bar displayed as localhost: 8889 / # 18 / / componentsB/Gene/male (port) according to their own set, indicating that the url will carry parameters by parameter.

1.2 params refs

First of all, restore the modified part of the route configuration just now, and add the button “Mode 2 jump to Component B” on the Componentsa. vue page:

componentsA.vue

<template> <div> <div> I am component A</div> < button@click ='routerToB1'</button> < button@click ='routerToB2'</button> </div> </template>Copy the code

Add method routerToB2 to methods, use the route attribute name to determine the matched route, and use the attribute params to pass parameters:

componentsA.vue

			routerToB2(){
				this.$router.push({
					name:'componentsB',
					params:{
						exa:'I'm a parameter passed to component B'}})},Copy the code

ComponentsB vue remains unchanged, params to obtain parameters by parameter through this. $route. Params, click the newly added A page button “B” way to jump to two components, in pages to print out {B exa: } localhost:8889/#/componentsB {localhost:8889/#/componentsB}

1.3 the query parameter

Componentsa.vue: ComponentSa.vue: ComponentSa.vue: ComponentSa.vue: ComponentSa.vue: ComponentSa.vue

componentsA.vue

<template> <div> <div> I am component A</div> < button@click ='routerToB1'</button> < button@click ='routerToB2'</button> < button@click ='routerToB3'</button> </div> </template>Copy the code

Add method routerToB3 to methods, use the route attribute name or Path to determine the matched route, and use the route attribute query to pass parameters:

componentsA.vue

			routerToB3(){
				this.$router.push({
					name:'componentsB',// path:'/componentsB'
					query:{
						que:'I'm passing a parameter to component B via query'}})}Copy the code

$route.query (componentsB. Vue);

componentsB.vue

			getRouterData(){
				const query = this.$route.query
				console.log(query)//{que: "I'm passing parameters to component B via query."}}Copy the code

Localhost :8889/#/componentsB? Que = I’m passing the parameter to component B via query, which is obviously the way the URL carries the parameter.

1.4 summary

  • Note The format of the route configuration parameter/:id, the parameters are obtained through$routeRather than$router
  • paramsTo participate andqueryThe difference between passing parameters is similar topostandgetMethods.paramsThe address bar does not display parameters, whilequeryThe parameters are displayed in the address bar
  • paramsPass parameters refresh page parameters are lost, the other two are not
  • paramsThe route attribute corresponding to the parameter isnameAnd thequeryThe route attribute corresponding to the parameter can be eithernameOr it could bepath

Two, the use of cache

The caching mode is to pass parameters through sessionStorage, localStorage and Cookie. This mode has nothing to do with whether Vue is used or not, therefore, not to talk about.

Three, father and son components between the value

In the components directory, create the parent component parent-vue and the child component children.vue, and introduce the child component into the parent component. For demonstration purposes, add the /parent path to the route configuration.

3.1 A parent Component Passes Value to a child component

In children. Vue, props is used to receive message1. If the value passed is a variable, use v-bind: or:, as shown below:

parent.vue

<template> <div> <div> I am the parent component </div> <children message1='I'm the direct argument.' v-bind:message2='msg' :message3='obj'></children>
	</div>
</template>

<script>
	import Children from './children'
	export default{
		components:{
			Children
		},
		data() {return{
				msg:'I'm an argument to the parent component'}},created(){
			this.obj = {a:'1',b:'2',c:'3'}
		}
	}
</script>

<style>
</style>
Copy the code

children.vue

< the template > < div > < div > I am a child component < / div > < div > {{message1}} < / div > < div > {{message2}} < / div > < div > {{message3}} < / div > < / div > </template> <script>export default{
		props:['message1'.'message2'.'message3'].created(){
			console.log(this.message3)
		}
	}
</script>

<style>
</style>Copy the code

Open it in a browser:



3.2 Child component passes $emit to parent component

The child component fires events on the current instance via vm.$emit(event, [… args]). Additional parameters are passed to the listener callback. The parent component listens for events on the child component label to get parameters.

children.vue

<template>
	<div style="margin-top: 100px;"> < div > I am a child component < / div > < div > {{message1}} < / div > < div > {{message2}} < / div > < div > {{message3}} < / div > < button @ click ='ChildToParent'</button> </div> </template> <script>export default{
		props:['message1'.'message2'.'message3'].data() {return{
				loud:'I love xx'
			}
		},
		methods:{
			ChildToParent(){
				this.$emit('emitToParent',this.loud)
			}
		},
		created(){
			console.log(this.message3)
		}
	}
</script>

<style>
</style>
Copy the code

parent.vue

<template> <div> <div> I am the parent component </div> <div> Tell me out loud who you love: {{loveWho}}</div> <children @emittoparent ='parentSayLove' message1='I'm the direct argument.' v-bind:message2='msg' :message3='obj'></children>
	</div>
</template>

<script>
	import Children from './children'
	export default{
		components:{
			Children
		},
		data() {return{
				msg:'I'm an argument to the parent component',
				loveWho:' '
			}
		},
		methods:{
			parentSayLove(data){
				this.loveWho = data
			}
		},
		created(){
			this.obj = {a:'1',b:'2',c:'3'}
		}
	}
</script>

<style>
</style>Copy the code

Click the button to display the browser:



3.3 summary

  • propsIt can be an array of strings or an object (you can type validate, set defaults, and so on);

  • use.nativeModifier listener events, used in developmentelement-ui Using event binding is invalid when using frame tags. You need to use.nativemodifiedv-on:eventYou can listen for a native event on a frame tag or on the root element of a component, for example<my-component v-on:click.native="doTheThing"></my-component>.

Four, non father and son (brother) components between the value

To transfer values between non-parent and child components, you need to define a public instance file, bus.js, as an intermediate repository for transferring values; otherwise, the effect of transferring values between routing components cannot be achieved. Create first.vue and second.vue and the public file bus.js under the Components directory.

bus.js

import Vue from 'vue'
export default new Vue()Copy the code

Bus.js is introduced in first.vue and second.vue respectively.

	import Bus from '.. /bus.js'Copy the code

Simulation scenario: First. vue transmits values to second.vue. $emit(event, [… args]) in first.vue and Bus.$on(event,callBack) in second.vue

first.vue

<template> <div> <div> I am first. Vue </div> < button@click ="firstToSecond"</button> </div> </template> <script> import Bus from'.. /bus.js'
	export default{
		data() {return{
				msg:'I am a parameter passed from first.vue to second.vue'
			}
		},
		methods:{
			firstToSecond(){
				Bus.$emit('emitToSecond',this.msg)
			}
		}
	}
</script>

<style>
</style>Copy the code

second.vue

<template> <div> <div> I am second. Vue </div> {{info}} </div> </template> <script> import Bus from'.. /bus.js'
	export default{
		data() {return{
				info:' '}},mounted(){
			const that = this;
			Bus.$on('emitToSecond'.function(data){
				that.info = data
			})
		}
	}
</script>

<style>
</style>Copy the code

Click the button and the browser will display:



summary

The communication between siblings is similar to that between children sending value to their parents. For example, children send value to their parents in the form of $emit and $ON without Bus. However, if we think about it carefully, The parent component acts as the event Bus.

5. Use Vuex

Here’s what Vuex is:

Vuex was developed specifically for vue.js applications
Status management mode. It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way.



When is Vuex used?

Vuex helps us manage shared state and comes with more concepts and frameworks. This requires a trade-off between short-term and long-term benefits.

Using Vuex can be tedious and redundant if you don’t plan to develop large, single-page applications. That’s true — if your application is simple, you’d better not use Vuex. A simple Store pattern is all you need. However, if you need to build a medium to large single-page application, and you’re probably thinking about how to better manage state outside of components, Vuex would be a natural choice.

Create vuexa. vue and vuexb. vue in the Components directory. Simulation scenario: Vuexa. vue transmits values to vuexb. vue.

NPM install vuex –save, create vuex directory in SRC, and create index.js, state.js, getters. Js, actions.js, mutations.



vuex/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state.js'
import mutations from './mutations.js'
import getters from './getters.js'
import actions from './actions.js'
Vue.use(Vuex)

export default new Vuex.Store({
	state,
	getters,
	mutations,
	actions
})Copy the code

Add vuex/index.js to main.js and inject it into Vue:

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './vuex'
Vue.config.productionTip = false

new Vue({
	store,
	router,
  render: h => h(App),
}).$mount('#app')
Copy the code

state.js

export default{
	city:'nanjing'
}Copy the code

vuexA.vue

<template> <div> <div> I am vuexA city parameter: {{city}}</div> <inputtype="text" :value="city" @change="change">
	</div>
</template>

<script>
	export default{
		methods:{
			change(e){
				this.$store.dispatch('setCityName',e.target.value)
			}
		},
		computed:{
			city() {return this.$store.getters.getCity
			}
		}
	}
</script>

<style>
</style>Copy the code

vuexB.vue

{{city}}</div> </div> </template> <script>export default{
		data() {return{
				
			}
		},
		computed:{
			city() {return this.$store.state.city
			}
		}
	}
</script>

<style>
</style>
Copy the code

actions.js

export default{
	setCityName({commit,state},name){
		commit('setCity',name)
	}
}Copy the code

mutations.js

export default{
	setCity(state,name){state. City = name// set new value}}Copy the code

getter.js

export default{
	getCity(state){
		returnState. City // Return the current city name}}Copy the code

Open it in a browser:



Modify the value in the input:



Obviously, when the input value in the vuexA page changes, the value in the vuexB page can be changed at the same time, that is, the city parameter is transferred from the vuexA page to the vuexB page, so as to realize the value transfer in the component with VUex.

For more details about vuEX functions, please refer to the official VuEX Chinese documentation.


The entire instance code has been uploaded to my GitHub, welcome to Fork.

Vi. Reference documents

  1. Parameter transfer between parent and child components in VUE
  2. Vue communication, value transmission in a variety of ways
  3. Vuex implements value transfer between sibling components