vue组件间的数据使用

一、父子组件通信

  1. props/$emit
    App.vue
<template>
  <div id="app">
    <Bar></Bar>
  </div>
</template>
import Bar from './template/Bar'

Bar.vue

<template>
    <Foo title='Foo to Bar' @getMessage='handleMessage'></Foo>
</template>
<script>
import Foo from './Foo'
export default {
    components: {
        Foo
    },
    methods: {
        handleMessage(data) {
            console.log(data)
        }
    },
}
</script>

Foo.vue

<template>
    <div>
        <h1>the message from Bar: {{ title }}</h1>
        <button @click='toParent'>send</button>
    </div>
</template>
<script>
export default {
    name: 'Foo',
    props: ['title'],
    methods: {
        toParent() {
            this.$emit('getMessage','Foo to Bar')
        }
    },
}
</script>
  1. $refs/ref
    可以获取组件实例,通过调用组件实例的方法来通信
    App.vue
<template>
  <div id="app">
    <Bar></Bar>
  </div>
</template>
<script>
import Bar from './components/Bar'
export default {
  name: "App",
  components: {
    Bar
  }
};
</script>

Bar.vue

<template>
    <div>
        <Foo ref='foo'></Foo>
        <button ref='btn' @click='getFoo'>getfoo</button>
    </div>
</template>
<script>
import Foo from './Foo'
export default {
    components: {
        Foo
    },
    methods: {
        getFoo(){
            // 通过ref给组件取名字,通过$refs来获取组件信息
            // 获取子组件的方法来传参
            this.$refs.foo.setTitle('Bar said new title')
            // ref写在原生组件上,直接获取该DOM
            console.log(this.$refs.btn)
        }
    },
}
</script>

Foo.vue

<template>
    <div>
        {{ newTitle }}
    </div>
</template>
<script>
export default {
    name: 'Foo',
    data() {
        return {
            newTitle: ''
        }
    },
    methods: {
        setTitle(newData) {
            this.newTitle = newData
        },

    },
}
</script>
  1. $parent/children
    Bar.vue
<template>
    <div>
        <Foo></Foo>
        <button @click='getFoo'>getfoo</button>
    </div>
</template>
<script>
import Foo from './Foo'
export default {
    components: {
        Foo
    },
    methods: {
        getFoo(){
            this.$children[0].setInfo('im Bar')
        }
    },
}
</script>

Foo.vue

<template>
    <div>
        {{ title }}
        <button @click='getDadInfo'>getDadInfo</button>
    </div>
    
</template>
<script>
export default {
    name: 'Foo',
    data() {
        return {
            title: 'im Foo'
        }
    },
    methods: {
        getDadInfo(){
            // 可以获取父组件信息
            console.log(this.$parent)
        },
        setInfo(newTitle){
            this.title = newTitle
        }

    },
}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值