Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the Page Refresh of parent and Child components by Vue

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the "Vue how to achieve parent-child component page refresh" related knowledge, editor through the actual case to show you the operation process, the method of operation is simple and fast, practical, hope that this "Vue how to achieve parent-child component page refresh" article can help you solve the problem.

In many cases, the data will change when we have manipulated the page, especially after the addition, deletion and modification operations. At this time, we want the data in the returned interface to be synchronized with the data in the database, so we need to refresh the current page. If you can use ajax to partially refresh the page, you can use asynchronous requests to refresh the page. Several common Vue page refresh methods are as follows:

1. Reload the page in place (not recommended) this.$router.go (0) / / redirect to the current page or location.reload () / / reload the current page according to the route

The above two methods can synchronize data, but in fact, the current page is reloaded, and the screen flashes when it is refreshed. If the current page initializes the loaded data or requests a lot, this method seriously affects efficiency and experience.

2. Blank page as a transition

Create a new blank page component empty.vue, click OK to jump to the blank page, and then immediately jump back to the current page.

Introduce a blank page component to the page that needs to be refreshed, and then add a route jump:

/ / introduce blank page component import empty from'@ / views/organization/empty.vue'// to add route jump this.$router.replace ({path:'/empty'})

This method and the above two methods, there will not be an instant blank page (if the network is not good or a large amount of data may also appear), but the address bar has a fast switching process, if the amount of data is not large can also be used.

3. Use Provide / Inject combination to control display

For more information, please refer to the official website guidance document.

Typically, we use props when we need to pass data from the parent component to the child component. Imagine a structure where there are some deeply nested components, while deep child components require only part of the parent component. In this case, it can be troublesome to still pass the prop step by step along the component chain.

In this case, we can use a pair of provide and inject. No matter how deep the component hierarchy is, the parent component can act as a dependent provider for all its child components. This feature has two parts: the parent component has a provide option to provide data, and the child component has an inject option to start using the data.

The most basic Vue scaffolding project of this method is easy to implement:

Define variables and methods in App.vue and components as follows:

Export default {name: 'App', provide () {/ / provides variables in the parent component through provide, and injects variables in the child component through inject. Return {reload:this.reload}}, data () {return {isShow:true / / variables that control whether the view is displayed}}, methods: {reload () {this.isShow=false / / close this.$nextTick first (() = > {this.isShow=true / / reopen})}

Use inject to inject the reload method of the root component in the subcomponent:

Refresh the page export default {data () {return {}}, inject: ['reload'] / / inject injects the reload method methods of the root component: {update () {this.reload () Console.log ('Refresh Page')}

But the vue project I use is based on webpack, and the overall project structure is a little different, and I haven't worked it out for a long time:

Import {Component, Vue} from 'vue-property-decorator' @ Component ({name:' App', provide () {/ / parent component through provide to provide variables, and inject to inject variables in child components. Reload: this.reload}, data () {return {isRouterAlive: true / / variable that controls whether the view is displayed}} Method: {reload () {this.isRouterAlive = false / / close this.$nextTick first (() = > {this.isRouterAlive = true / / reopen})}}) export default class extends Vue {}

Reload is injected into the subcomponent:

Import {updateStore,// updates store information getStoresData,// gets store list information searchStore// obtains store information according to store id and merchant id} from'@ / api/organization.ts' import App from'@ / App.vue' @ Component ({components: {updateStore, getStoresData SearchStore}}) / * the default output here is the integrated Vue class (similar to the entity class defined in java) * / export default class createTasks extends Vue {/ / inject relod inject here: ['reload'] Private async ensureDialog () {let res = await updateStore (this.form) this.syncDialogVisible = false; if (res) {this.$message.success ('modified successfully');} / / indicates that the request response is successful this.reload () / / call the reload method of the root component here}}

The above practice does not take effect, if a great god knows which is wrong, please do not hesitate to give us advice.

4. V-on:param parent component listens for child component events

We know that Vue has a characteristic. As long as the value of the data attribute in the vue instance changes, the data bound to render using v-model or: data in the page will also change accordingly. Usually, the interface for displaying the data is the parent component, and when you need to add, delete, modify and check a piece of data in the parent component, it will respond to pop-up a component box suspended above the parent component to display the contents of a piece of data separately. And this suspension component can be seen as a sub-component.

So as long as we listen to the behavior events of the child components in the parent component, we can refresh the local data of the current page (not reload).

Parent component: index.vue

Store Management import addStore from'@ / views/organization/addStore.vue' import Pagination from "@ / components/Pagination/index.vue" Import setCode from'@ / views/organization/setCode.vue' import updateStore from'@ / views/organization/updateStore.vue' import setUse from'@ / views/organization/setUse.vue' @ Component ({components: {addStore, Pagination, setCode, updateStore, setUse}}) export default class extends Vue {private list: any [] = [] Private pageNo: number = 1; private pageSize: number = 10; private total: number = 0; private dialogVisible: boolean = false; private dialogVisible1: boolean = false; private dialogVisible2: boolean = false; private dialogVisible3: boolean = false; private appId: string ='; private codes: string =''; private storeId: string ='' Private storeForm = {storeName:', storeNumber:''} private form = {totalAmount:', body:''} created () {this.getList ()} private async getList () {let data = await getStoresData (this.pageNo, this.pageSize) This.storeForm) this.list = data.items / / list of stores queried this.total = this.list.length; / / Total number of records queried}}

You can see that the above parent component contains the following child components:

/ / add store sub-components / / update door store sub-components

The purpose of the getList method is to update the data to be displayed by the current parent component:

Private async getList () {let data = await getStoresData (this.pageNo, this.pageSize, this.storeForm) this.list = data.items; / / list of stores queried}

GetStoresData method:

/ / query the merchant's stores under paging conditions export const getStoresData = (pageNo:number,pageSize:number,data:any) = > request ({url: `/ merchant/my/stores/merchants/page?pageNo=$ {pageNo} & pageSize=$ {pageSize} & tenantId=$ {UserModule.tenantId}`, method: 'post', data})

Render the data:

This.list = data.items; / / list of stores queried

Update data subcomponent updaStore.vue:

Cancel the deterministic @ Component ({components: {updateStore, getStoresData, searchStore}) export default class createTasks extends Vue {@ PropSync ('dialogVisible', {type: Boolean, default: false}) syncDialogVisibleVerification: boolean @ PropSync (' storeIds' {type: String}) storeIdstores: string private form = {id: 0, storeAddress:', storeName:', storeNumber: 0, parentId: 0, storeStatus:', merchantId: 0} private storeForm = {storeNumber:'' StoreName:''} list: any [] = [] PageNo: number = 1; pageSize: number = 10; total: number = 0; private filterData: any [] = []; private opend () {this.getList ();} private async getList () {let res = await searchStore (this.storeId); this.form = res.result } private async ensureDialog () {let res = await updateStore (this.form) this.syncDialogVisible = false; if (res) {this.$message.success ('modified successfully');}

Practical application scenarios:

In the sub-component updateStore.vue, click OK to modify. After the modification is successful, query the store list getStoresData in the current component:

Private async ensureDialog () {let res = await updateStore (this.form) this.syncDialogVisible = false; if (res) {this.$message.success ('modified successfully');} / / query list information here let ret = await getStoresData (this.pageNo, this.pageSize, this.storeForm) This.list = ret.items; this.total = this.list.length;}

According to the theory is to query the modified store list list, but currently in the child component, list and the parent component index.vue in the list scope is different, so the content in the parent component will not change synchronous update, then how to do?

As we said above, we need the parent component to listen to the events of the child component. After the child component completes the corresponding operation request, it can trigger the callback function that the parent component listens to, and let its parent component index.vue update the list and refresh the data in the page.

In the parent component index.vue:

/ / Update the door store sub-components

The put in the put is a triggering event of the listening child component, so we can trigger this event after completing the put update request in the child component and let the parent component update the rendered data synchronously.

There are two ways to complete synchronous updates here:

The child component directly triggers the listening event of the parent component, and the parent component queries the list information

The child component will query the list information and pass it to the parent component while triggering the listening event

The first way: directly trigger the listening event

Private async ensureDialog () {let res = await updateStore (this.form) this.syncDialogVisible = false; if (res) {this.$message.success ('modified successfully');} / / trigger parent component listening event put this.$emit ('put') } / / the parent component listens to the event putv-on:put= "getList" / / calls the getList method to re-query the list information (where this.list is the binding property of the rendering interface), thus completing the data refresh without reloading the entire page private async getList () {let data = await getStoresData (this.pageNo, this.pageSize, this.storeForm) this.list = data.items / / list of stores queried this.total = this.list.length; / / Total number of records queried}

The second way is to transmit data while triggering listening events.

Private async ensureDialog () {let res = await updateStore (this.form) this.syncDialogVisible = false; if (res) {this.$message.success ('modified successfully');} / / query list information here let ret = await getStoresData (this.pageNo, this.pageSize, this.storeForm) Let = ret.items; = this.list.length; / / triggers the parent component to listen for the event put while passing data (followed by parameter data) this.$emit ('put',ret.items,ret.items.length) } / / the parent component listens to the event putv-on:put= "getList" / / performs synchronous update rendering based on the data passed by the child component (the number of parameter lists in this method should be the same as the number of parameters passed by the listening event) private async getList (param1,param2) {this.list = param1; / / list data passed by the child component this.total = param2 / / number of list records passed by subcomponents}

The addStore.vue subcomponent can also use this method to complete synchronous update rendering.

This is the end of the content about "how Vue implements the page refresh of parent and child components". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report