1. From father to son (1) Bind a property to the child component tag of the parent component and mount the variable to be transferred. (2) Accept data through props in the child component. Props can be an array or an object. The received data can be directly used props: ["property name"] props:{property name: data type} //Parent component <template> <div> <i>Parent component</i> <!--Page usage--> <son :data='name'></son> </div> </template> <script> import son from "./son.vue"; //Import parent component export default { components: { son }, //Register component name: "parent component", data() { return { name: "Frazier", //parent component defines variables}; }, }; </script> //Subcomponent <template> <div>{{data}}</div> </template> <script> export default { components: { }, name: 'Subcomponent', props:["data"], }; </script> 2. Son to Father (1) Customize an event on the child component tag of the parent component and then call the required method. //Parent component <template> <div> <i>Parent component</i> <!--Page usage--> <son @lcclick="lcclick"></son>//Customize an event</div> </template> <script> import son from "./son.vue"; //Import parent component export default { components: { son }, //Register component name: "parent component", data() { return {}; }, methods: { lcclick(){ alert('son passes on to father') } }, }; </script> //Subcomponent <template> <div> <button @click="lcalter">Click me</button> </div> </template> <script> export default { components: { }, name: 'Subcomponent', methods: { lcalter(){ this.$emit('lcclick')//Trigger the event through emit} }, }; </script> 3. Brother component communication (bus) (1) Create a new Bus.js file in src and export an empty vue instance Image examples: 4. ref/refs (parent-child component communication) (1) If ref is used on a normal DOM element, the reference points to the DOM element; if it is used on a child component, the reference points to the component instance. //Parent component <template> <div> <button @click="sayHello">sayHello</button> <child ref="childForRef"></child> </div> </template> <script> import child from './child.vue' export default { components: { child }, data () { return { childForRef: null, } }, mounted() { this.childForRef = this.$refs.childForRef; console.log(this.childForRef.name); }, methods: { sayHello() { this.childForRef.sayHello() } } } </script> //Subcomponent <template> <div>child's content</div> </template> <script> export default { data () { return { name: 'I am a child', } }, methods: { sayHello() { console.log('hello'); alert('hello'); } } } </script> 5. Vuex communication Components dispatch to actions, which are asynchronous operations. Actions commit to mutations, which change the state through logical operations, thereby synchronizing to components and updating their data status. //parent component template> <div id="app"> <ChildA/> <ChildB/> </div> </template> <script> import ChildA from './ChildA' // Import component A import ChildB from './ChildB' // Import component B export default { components: {ChildA, ChildB} // Register components} </script> //Subcomponent A <template> <div id="childA"> <h1>I am component A</h1> <button @click="transform">Click me to let component B receive data</button> <p>Because B was clicked, the message changed: {{BMessage}}</p> </div> </template> <script> export default { data() { return { AMessage: 'Hello, component B, I am component A' } }, computed: { BMessage() { // Store the data of component B obtained from the store here return this.$store.state.BMsg } }, methods: { transform() { // Trigger receiveAMsg and store the data of component A in the store this.$store.commit('receiveAMsg', { AMsg: this.AMessage }) } } } </script> //Subcomponent B <template> <div id="childB"> <h1>I am component B</h1> <button @click="transform">Click me to let component A receive data</button> <p>Click A, my message changes: {{AMessage}}</p> </div> </template> <script> export default { data() { return { BMessage: 'Hello, component A, I am component B' } }, computed: { AMessage() { // Here we store the data of component A obtained from the store return this.$store.state.AMsg } }, methods: { transform() { // Trigger receiveBMsg and store the data of component B in the store this.$store.commit('receiveBMsg', { BMsg: this.BMessage }) } } } </script> //vuex import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const state = { AMsg: '', BMsg: '' } const mutations = { receiveAMsg(state, payload) { // Store the data of component A in state state.AMsg = payload.AMsg }, receiveBMsg(state, payload) { // Store the data of component B in state state.BMsg = payload.BMsg } } export default new Vuex.Store({ state, mutations }) 6. $parent Parent can be used to obtain the parent component instance, and then the properties and methods of the parent component can be accessed through this instance. It also has a brother parent that can obtain the parent component instance, and then the properties and methods of the parent component can be accessed through this instance. It also has a brother parent that can obtain the parent component instance, and then the properties and methods of the parent component can be accessed through this instance. It also has a brother root that can obtain the root component instance. // Get the parent component's data this.$parent.foo // Write data to the parent component this.$parent.foo = 2 // Access the parent component's computed property this.$parent.bar //Call the parent component method this.$parent.baz() //In the example of passing a child component to a parent component, you can use this.$parent.getNum(100) to pass the value to the parent component. 7.sessionStorage value transfer SessionStorage is a global object of the browser, and the data stored in it will be cleared when the page is closed. Using this feature, we can share a copy of data across all pages. // Save data to sessionStorage sessionStorage.setItem('key', 'value'); // Get data from sessionStorage let data = sessionStorage.getItem('key'); // Delete saved data from sessionStorage sessionStorage.removeItem('key'); // Delete all saved data from sessionStorage sessionStorage.clear(); Note: What is stored in it is key-value pairs, which can only be string types. If you want to store objects, you need to use let objStr = JSON.stringify(obj) to convert it into a string and then store it (when using let obj = JSON.parse(objStr) to parse it into an object). //localStorage storage.set(key,val) storage.get(key, def) //sessionStorage storage.session.set(key, val) storage.session.get(key, val) 8. Routing value Use question mark to pass value { path: '/b/:name', name: 'b', component: () => import( '../views/B.vue') }, On page B, you can use this.$route.params.name to get the value of name passed in by the route Use parent-child component to pass value Since router-view itself is also a component, we can also use parent-child component to pass value, and then add props to the corresponding child page. Because the route is not refreshed after the type is updated, the latest type value cannot be directly obtained in the mounted hook of the child page, but watch is used <router-view :type="type"></router-view> // Subpage props: ['type'] watch: type(){ // console.log("In this method, you can always get the latest data: type=", this.type) }, }, 9. Ancestor's grandchild $attrs Under normal circumstances, you need to use the props of the father as an intermediate transition, but in this way, the father component will have more attributes that are not related to the business of the parent component, and the coupling is high. With the help of $attrs, it can be simplified, and neither the grandparent nor the grandchild does not need to be modified. <template> <section> <parent name="grandParent" sex="男" age="88" hobby="code" @sayKnow="sayKnow"></parent> </section> </template> <script> import Parent from './Parent' export default { name: "GrandParent", components: Parent }, data() { return {} }, methods: { sayKnow(val){ console.log(val) } }, mounted() { } } </script> Parent Component <template> <section> <p>The parent component receives</p> <p>Grandfather's name: {{name}}</p> <children v-bind="$attrs" v-on="$listeners"></children> </section> </template> <script> import Children from './Children' export default { name: "Parent", components: Children }, // The parent component receives the name, so the name value will not be passed to the child component's props:['name'], data() { return {} }, methods: {}, mounted() { } } </script> Subcomponents <template> <section> <p>Subcomponent received</p> <p>Grandfather's name: {{name}}</p> <p>Grandfather's gender: {{sex}}</p> <p>Grandfather's age: {{age}}</p> <p>Grandfather's hobby: {{hobby}}</p> <button @click="sayKnow">I know</button> </section> </template> <script> export default { name: "Children", components: {}, // Since the parent component has received the name attribute, name will not be passed to the child component props:['sex','age','hobby','name'], data() { return {} }, methods: { sayKnow(){ this.$emit('sayKnow','I know') } }, mounted() { } } </script> 10. Sun Chuanzu uses $listenersSame as the ninth one Ancestor Components <template> <div id="app"> <children-one @eventOne="eventOne"></children-one> {{ msg }} </div> </template> <script> import ChildrenOne from '../src/components/children.vue' export default { name: 'App', components: ChildrenOne, }, data() { return { msg: '' } }, methods: { eventOne(value) { this.msg = value } } } </script> Parent Component <template> <div> <children-two v-on="$listeners"></children-two> </div> </template> <script> import ChildrenTwo from './childrenTwo.vue' export default { name: 'childrenOne', components: ChildrenTwo } } </script> Subcomponents <template> <div> <button @click="setMsg">Click to pass to grandfather</button> </div> </template> <script> export default { name: 'children', methods: { setMsg() { this.$emit('eventOne', '123') } } } </script> 11. Promise parameter passingHow to pass multiple parameters in promise resolve //Similar to this usage, but in fact the last two parameters cannot be obtained promise = new Promise((resolve,reject)=>{ let a = 1 let b = 2 let c = 3 resolve(a,b,c) }) promise.then((a,b,c)=>{ console.log(a,b,c) }) resolve() can only accept and process one parameter, and any extra parameters will be ignored. promise = new Promise((resolve,reject)=>{ resolve([1,2,3]) }) promise.then((arr)=>{ console.log(arr[0],arr[1],arr[2]) }) Object promise = new Promise((resolve,reject)=>{ resolve({a:1,b:2,c:3}) }) promise.then(obj=>{ console.log(obj.a,obj.b,obj.c) }) 12. Global variables Define a global variable, assign a value directly to the component with a value, and use it directly in the required component. For details, please refer to my blog. This concludes this article on the twelve methods of Vue value transfer. For more information on Vue value transfer, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Detailed explanation of system input and output management in Linux
>>: Detailed tutorial on installing MySQL 5.7.20 on RedHat 6.5/CentOS 6.5
Table of contents Question 1: How are props used ...
<br />Forms are an important channel for use...
<br />When you click the link, the web page ...
Current demand: There are two tables, group and f...
Preface I believe that everyone has been developi...
You must have inspiration to design a website. Goo...
MySQL executes SQL through the process of SQL par...
MySQL 5.7.13 installation tutorial for Mac, very ...
Here are some examples of how I use this property ...
TypeScript Bundling webpack integration Usually, ...
Introduction There is no need to introduce Redis ...
I searched a lot online and found that many of th...
I have been using the CentOS purchased by Alibaba...
Red and pink, and their hexadecimal codes. #99003...
<div class="sideBar"> <div>...