Get vue component data

You can quickly obtain the data of the parent component or child component through this.$parent.XXor . this.$children[0].XXHowever, it should be noted that the data obtained from the child component is an array, because there can be multiple children.

You can also this.refs.XXquickly obtain the attributes of subcomponents through this method. This method can also directly manipulate dom elements and change dom attributes close to native js.

parent code:

<template>
    <div>
        <h3>parent: 获取vue组件数据</h3>
        <p>我自己的数据info:{
   
   { info }}</p>
        <button @click="getsonData">获取son数据</button>
        <p>get son 的数据:{
   
   { getsonDatas }}</p>
        <hr>
        <son></son>
    </div>
</template>

<script>
import son from './son.vue';
export default {
      
      
    components:{
      
      
        son
    },
    data(){
      
      
        return{
      
      
            info:"我是parent中的数据",
            getsonDatas:""
        }
    },
    methods:{
      
      
        getsonData(){
      
      
            this.getsonDatas = this.$children[0].sonData
        }
    }
}
</script>

<style>

</style>

son code

<template>
    <div>
        <h4>son: 获取到父组件数据:{
   
   { info }}</h4>
        <h4>我自己的数据:{
   
   { sonData }}</h4>
        <button @click="getData">获取父组件的数据</button>
        <button @click="changeData">change父组件的数据</button>
    </div>
</template>

<script>
export default {
      
      
    data(){
      
      
        return{
      
      
            info:" ",
            sonData:"little son data"
        }
    },
    methods:{
      
      
        getData(){
      
      
            this.info = this.$parent.info
        },
        changeData(){
      
      
            this.$parent.info = "这就被修改了???no..."
            this.getData()
        }
    }
}
</script>

<style>

</style>

Realization effect:
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_44239550/article/details/128653529